I am using the Recipe DB API for a Recipe app I am building. So far I have the state of the query set to chicken which returns all the chicken recipes from the API. But whenever I look up something different, say ‘banana’, the state doesn’t change. I moved my getRecipes
function inside the useEffect
which got rid of the error message saying that useEffect
was missing a dependency. However, I still can’t get it to work. Here is my code so far:
import React, { useEffect, useState } from "react";
import Recipe from "./Recipe.js";
import "./styles.css";
export default function App() {
const API_ID = "c38daf94";
const API_KEY = "850d468a3e994692691631c7c259406c";
const [recipes, setRecipes] = useState([]);
const [search, setSearch] = useState("");
const [query, setQuery] = useState('chicken');
useEffect(() => {
async function getRecipes() {
const response = await fetch(
`https://api.edamam.com/search?q=${query}&app_id=${API_ID}&app_key=${API_KEY}`
);
const data = await response.json();
setRecipes(data.hits);
console.log(data.hits);
}
if (query !== "") getRecipes();
}, [query]);
// const getRecipes = async () => {
// const response = await fetch(
// `https://api.edamam.com/search?q=${query}&app_id=${API_ID}&app_key=${API_KEY}`
// );
// const data = await response.json();
// setRecipes(data.hits)
// console.log(data.hits);
// };
const updateRecipes = e => {
setSearch(e.target.value);
};
const getSearch = e => {
e.preventDefault();
console.log(query)
setQuery(query);
};
return (
<div className="App">
<input
className="input"
onChange={updateRecipes}
value={search}
type="text"
/>
<button className="search" onClick={getSearch}>
Search
</button>
<div>
{recipes.map(recipe => (
<Recipe
key={recipe.recipe.uri}
title={recipe.recipe.label}
calories={recipe.recipe.calories}
image={recipe.recipe.image}
/>
))}
</div>
</div>
);
}