OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

React: Empty Array Displayed Before Asynchronous Data Fetched (Search Functionality)

  • Thread starter Thread starter yzkael
  • Start date Start date
Y

yzkael

Guest
I'm facing an issue with my React application's search functionality. When I submits a search term, the application initially displays an empty list of recipes. Yet by using console.log on my backend I quickly realize that it instantly sends the empty array yet after a while it correctly fetches the data im interested in... Since Its my first time practicing using APIs that are not locally hosted(I'm fetching information from spoonacular). I am not sure If I need to change something from my code:

This is my Backend APIs:

// recipe-api

export const searchRecipes = async (searchTerm:string,page:number)=>{ if (!apiKey) { throw new Error("API Key not found"); }

Code:
const url = new URL("https://api.spoonacular.com/recipes/complexSearch");

const queryParams = {
    apiKey: apiKey,
    query: searchTerm,
    number: "10",
    offset: (page * 10).toString(),
}

url.search = new URLSearchParams(queryParams).toString();

try {
    const searchResponse  = await fetch(url);
    console.log(searchResponse)
    const resultsJson = await searchResponse.json();
    return resultsJson;
} catch (error) {
    console.log(error);
} }

My frontend api:

//api-client

export const searchRecipes = async(search:string, page: number)=>{ const baseURL = new URL("http://localhost:3000/api/recipes/search");

Code:
baseURL.searchParams.append("searchTerms",search);
baseURL.searchParams.append("page",page.toString());

console.log(baseURL);
const response = await fetch(baseURL);

if(!response.ok){
    throw new Error(`Something went wrong.... ${response.status}`);
}

return response.json(); }

The submit handler and the element that its beeing called upon

//Handler

const [search, setSearchTerm] = useState("burgers"); const [recipes, setRecipes] = useState<Recipe[]>([]);

const handleSearchSubmit = async (event: FormEvent) => { event.preventDefault();

Code:
try {
  const recipesFound = await api.searchRecipes(search, 1);
  console.log(recipesFound);
  setRecipes(recipesFound.results);
} catch (error) {
  console.log(error);
}   };

// Element thats invoking the handler

Submit {recipes.map((recipe: Recipe) => ( recipe image location: {recipe.image} recipe title: {recipe.title} ))}

I'm fairly new to React, hooks and fetching. So any feedback is appreciated.

<p>I'm facing an issue with my React application's search functionality. When I submits a search term, the application initially displays an empty list of recipes. Yet by using console.log on my backend I quickly realize that it instantly sends the empty array yet after a while it correctly fetches the data im interested in... Since Its my first time practicing using APIs that are not locally hosted(I'm fetching information from spoonacular). I am not sure If I need to change something from my code:</p>
<p>This is my Backend APIs:</p>
<p>// recipe-api</p>
<blockquote>
<p>export const searchRecipes = async (searchTerm:string,page:number)=>{
if (!apiKey) {
throw new Error("API Key not found");
}</p>
<pre><code>const url = new URL("https://api.spoonacular.com/recipes/complexSearch");

const queryParams = {
apiKey: apiKey,
query: searchTerm,
number: "10",
offset: (page * 10).toString(),
}

url.search = new URLSearchParams(queryParams).toString();

try {
const searchResponse = await fetch(url);
console.log(searchResponse)
const resultsJson = await searchResponse.json();
return resultsJson;
} catch (error) {
console.log(error);
} }
</code></pre>
</blockquote>
<p>My frontend api:</p>
<p>//api-client</p>
<blockquote>
<p>export const searchRecipes = async(search:string, page: number)=>{
const baseURL = new URL("http://localhost:3000/api/recipes/search");</p>
<pre><code>baseURL.searchParams.append("searchTerms",search);
baseURL.searchParams.append("page",page.toString());

console.log(baseURL);
const response = await fetch(baseURL);

if(!response.ok){
throw new Error(`Something went wrong.... ${response.status}`);
}

return response.json(); }
</code></pre>
</blockquote>
<p>The submit handler and the element that its beeing called upon</p>
<p>//Handler</p>
<blockquote>
<p>const [search, setSearchTerm] = useState("burgers"); const
[recipes, setRecipes] = useState<Recipe[]>([]);</p>
<p>const handleSearchSubmit = async (event: FormEvent)
=> {
event.preventDefault();</p>
<pre><code>try {
const recipesFound = await api.searchRecipes(search, 1);
console.log(recipesFound);
setRecipes(recipesFound.results);
} catch (error) {
console.log(error);
} };
</code></pre>
</blockquote>
<p>// Element thats invoking the handler</p>
<blockquote>


Submit

{recipes.map((recipe: Recipe) => (

recipe image location: {recipe.image}
recipe title: {recipe.title}

))}

</blockquote>
<p>I'm fairly new to React, hooks and fetching. So any feedback is appreciated.</p>
 
Top