简体   繁体   中英

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM