[英]How to take an input value to fetch API data in React.js
I want to make a search input where the user inputs a type of food (eg pasta) and it takes the input and plugs it into the URL where it specified ${type} to display the recipes from Spoonacular.com to match that user input with .我想在用户输入某种食物(例如意大利面)时进行搜索输入,然后将输入插入到指定 ${type} 的 URL 中,以显示 Spoonacular.com 中的食谱以匹配该用户输入和 。
This is my Home.js这是我的 Home.js
import React, { useEffect, useState } from "react";
import axios from "axios";
import Recipe from "../components/Recipes";
function Home() {
const [food, setFood] = useState();
const [type, setType] = useState();
const URL = `https://api.spoonacular.com/recipes/complexSearch?apiKey=${APIKey}&query=${type}&number=2`;
function handleChange(e) {
setType(e.target.text);
}
useEffect(() => {
axios
.get(URL)
.then(function (response) {
setFood(response.data);
console.log(URL);
})
.catch(function (error) {
console.warn(error);
});
}, []);
return (
<main className="App">
<input
type="text"
placeholder="Name of food (e.g. pasta)"
onChange={handleChange}
/>
<button onClick={}>Get a Recipe</button>
<Recipe recipeList={food} />
</main>
);
}
export default Home;
and here is my recipe.js component这是我的 recipe.js 组件
import React from "react";
function Recipe({ recipeList }) {
if (!recipeList) return <></>;
return (
<div className="recipeCard">
<h1>{recipeList?.title}</h1>
<img src={recipeList?.image} alt="Food" />
</div>
);
}
export default Recipe;
You need to specify the GET query parameters to the axios call.您需要为 axios 调用指定 GET 查询参数。 When you are defining the URL, type , which is the user input, is not yet defined.
在定义 URL 时,用户输入的type尚未定义。
const URL = `https://api.spoonacular.com/recipes/complexSearch`;
const params = {
apiKey: yourImportedApiKey,
number: 2,
query: type
};
// get recipe
const getRecipe = () => {
axios
.get(URL, params)
.then(function (response) {
setFood(response.data);
console.log(URL);
})
.catch(function (error) {
console.warn(error);
});
}
Then point onClick to the submit handler name you chose for your axios call.然后将onClick指向您为 axios 调用选择的提交处理程序名称。
<button onClick={getRecipe}>Get a Recipe</button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.