In a React project, I'am calling API to search recipes and load recipe on button click. My intention is to serve single API for both functions. Is there any appropriate solution?
- App.js
const [query, setQuery] = useState("porridge");
const [recipes, setRecipes] = useState([]);
const [alert, setAlert] = useState("");
// const [checked, setChecked] = useState(false);
const [radioValue, setRadioValue] = useState('1');
const radios = [
{ name: 'Chicken', value: 'chicken', active: true},
{ name: 'Bread', value: 'bread' },
{ name: 'Fish', value: 'fish' },
{ name: 'Soup', value: 'soup' },
{ name: 'Rice', value: 'rice' },
{ name: 'Meat', value: 'meat' }
];
const url = `https://cors-anywhere.herokuapp.com/https://api.edamam.com/search?
q=${query}&app_id=${APP_ID}&app_key=${APP_KEY}&from=0&to=12`;
{/* Load recipes on submit button click */}
const getData = async () => {
if (query !== "") {
const result = await Axios.get(url);
console.log(result)
if (!result.data.more) {
return setAlert("No food with such name");
}
setRecipes(result.data.hits);
setQuery("");
setAlert("");
} else {
setAlert("Please fill the form");
}
};
const onChange = e => setQuery(e.target.value);
const onSubmit = e => {
e.preventDefault();
getData();
};
{/* Load recipes on radio button click */}
const handleChange = async (e) => {
let checkValue = e.target.value;
if(checkValue) {
const result2 = await Axios.get(`https://cors-anywhere.herokuapp.com/https://api.edamam.com/search?q=${checkValue}&app_id=${APP_ID}&app_key=${APP_KEY}&from=0&to=12`);
setRecipes(result2.data.hits);
}
}
{/* Submit Button */}
<form onSubmit={onSubmit} className="search-form">
{alert !== "" && <Alert alert={alert} />}
<input
type="text"
name="query"
onChange={onChange}
value={query}
autoComplete="off"
placeholder="Search Food"
/>
<input type="submit" value="Search" />
<br/>
</form>
{/* Radio Button */}
<ButtonGroup toggle style={{width:'100%'}}>
{radios.map((radio, idx) => (
<ToggleButton
key={idx}
type="radio"
active="true"
variant="light"
name="radio"
value={radio.value}
checked={radioValue === radio.value}
onChange={(e) => {
handleChange(e);
setRadioValue(e.currentTarget.value)
}}
size="lg"
>
{radio.name}
</ToggleButton>
))}
</ButtonGroup>
<div className="recipes">
{recipes !== [] &&
recipes.map(recipe => <Recipe key={uuidv4()} recipe={recipe} />)}
</div>
As seen from above I've to call API two times, it would be better if same API is used for both functions. I tried to call from main API but query is not updated. Event value which I'am getting from radio button can't be taken as query outside function. So any better solution to tackle?