Home > other >  i am not able to map the api data array i have tried several methods from last two days
i am not able to map the api data array i have tried several methods from last two days

Time:01-13

Here is the simple code which fetches api recipes and prints them as cards :

import { useState } from "react";
import RecipeItem from "../../components/recipe-item";
import Search from "../../components/search";

const Homepage = () => {
  const [loadingstate, setloadingstate] = useState(false);

  const [recipes, setrecipes] = useState([]);

  const getdatafromsearchcomponent = (searchdata) => {
    setloadingstate(true);

    async function getrecipes() {
      const apiresponse = await fetch(
        `https://api.spoonacular.com/recipes/complexSearch?apiKey=2aa0ee8853c34e1f9783e0f882c40f38&query=${searchdata}`
      );
      const result = await apiresponse.json();
      const { results } = result;

      if (results && results.length > 0) {
        setloadingstate(false);
        setrecipes();
      }
      console.log(result);
    }
    getrecipes();
  };

  console.log(loadingstate, recipes, "loadingstate recipes");


  return (
    <div className="homepage">
      <Search getdatafromsearchcomponent={getdatafromsearchcomponent} />

      {loadingstate && (
        <div className="loadingmsg">loading.... please wait</div>
      )}
      {
       recipes && recipes.length>0?
       recipes.map((item)=>           /*THIS PART IS NOT WORKING*/
       <RecipeItem  item={item} />)
       :null
       }
    </div>
  );
};
export default Homepage;

recipe-item component below :

const RecipeItem=(props)=>{
    console.log(props,'recipe-item-props');
    return(
        <div>
            search result
        </div>
    )
}
export default RecipeItem;

I am trying to map the recipes i fetched from spoonacular api its fetchinf fine and shows data in the console but does not work when i try to map it on homepage

I tried to merge the search component to the homepage but that also did not work.

even the loading part is working fine the api fetch loading text shows on homepage but once the fetch over no data is visible on mapping although the fetched data is clearly visible on the console

and sorry for posting the entire code almost.

CodePudding user response:

Based on your code I can see that you are destructuring results but not set in the setrecipes properly, you have to set it like this setrecipes(results) after setloadingstate(false); inside the if condition.

  • Related