#javascript #node.js #rest #axios
#javascript #node.js #rest #axios
Вопрос:
У меня есть вызов API, чтобы показать некоторые ингредиенты, и пользователь может выбрать, какой ингредиент он хочет отфильтровать, и должен запустить фильтр в том же Axios GET API
Это вызов API, который выполняется, когда приложение загружает этот экран:
let recipeRequest = 'http://localhost:3333/report'
let ingredientsRequest = 'http://localhost:3333/ingredients'
useEffect(() => {
recipeRequest = axios.get(recipeRequest, {params:{name:nameArr}})
ingredientsRequest = axios.get(ingredientsRequest)
axios.all([recipeRequest, ingredientsRequest])
.then(axios.spread((...responses) => {
setRecipes(responses[0].data)
setIngredientList(responses[1].data)
}))
.catch(function (error) {
console.log('API CALL - recipe/ingredient - error: ', error);
})
},[])
со всеми данными, представленными пользователю, он может выбрать нужный ингредиент, и он должен отфильтровать соответствующий рецепт.
Это плоский список со всеми данными об ИНГРЕДИЕНТАХ
<FlatList
horizontal
bounces={false}
data={ingredientList}
renderItem={({ item, index }) => (
<TouchableOpacity key={item.id} onPress={() => selectedIngredient(item, index)}>
<Card key={index}>
{item.isSelected ? (
<>
<Text key={item.title} style={styles.titleText}>{item.name}</Text>
<Text style={{ color: "green" }}>{"Selected"}</Text>
</>
) : (
<>
<Text key={item.title} style={styles.titleText}>{item.name}</Text>
<Text style={{ color: "red" }}>{"Not Selected"}</Text>
</>
)}
</Card>
<ImageBackground key={item.illustration} source={item.illustration} style={styles.cardImage}>
</ImageBackground>
</TouchableOpacity>
)
}
keyExtractor={(item) => item.index}
/>
Это фильтр, который запускается, когда пользователь выбирает ингредиент в flatlist
let obj = ingredientList.filter(field => field.isSelected === true)
const nameArr = obj.map(arr => arr.name);
Как только «nameArr» будет обновлен, как я могу повторно вызвать переменную «recipeRequest» с этим «nameArr» в «params», чтобы правильно отфильтровать запрос?
Ответ №1:
Я создал функцию с именем «filteredRecipe», которая вызывается при событии onPress кнопки на этом экране. Итак, основная проблема решена, но теперь я столкнулся с другой проблемой, но это будет другой вопрос, большое спасибо за помощь.
const filteredRecipe = () => {
const filteredRecipe = recipeRequest "?name=" nameArr
axios.get(filteredRecipe)
.then((response) => {
console.log('(response): ', response)
setRecipes(response)
})
.catch(function (error) {
console.log('API CALL - recipe/ingredient - error: ', error);
})
}