skip to Main Content
function RecipesList() {
  //use effect to
  useEffect(() => {
    const getRecipesList = async () => {
      const response = await fetch("http://localhost:4000/recipe/allrecipes", {
        method: "GET",
      });
      const json = await response.json();

      if (response.ok) {
        setData(json);
        const allCategories = [
          "all",
          ...new Set(data.map((item) => item.category)),
        ];
        setCategories(allCategories);
      }
    };

    getRecipesList();
    //get all categories from data
  }, []);
}

Want to populate categories array base on data array

Data array is populated from databse

2

Answers


  1. Chosen as BEST ANSWER

    my problem is setData[] does not populate on 1st page render, on 2nd refresh it's working. I want to populate the data array on the first visit to the page

         useEffect(() => {
          const getRecipesList = async () => {
            const response = await fetch("http://localhost:4000/recipe/allrecipes", {
              method: "GET",
             });
            const json = await response.json();
            if (response.ok) {
              let newData = json;
              setData((preData) => [...preData, newData]);
              console.log(data);
    
             /*const allCategories = [
                "all",
                ...new Set(json.map((item) => item.category)),
             ];
              setCategories(allCategories);*/
            }
            if (!response.ok) {
              console.log(json.err);
              }
          };
           getRecipesList();
          //get all categories from data
       }, []);
    

  2. I think there’s a couple of issues if this is the complete code. You need to define the states for categories and data, eg:
    const [data, setData] = useState();
    and
    const [categories, setCategories] = useState(); at the top of the function.

    Also, you are trying to use data.map immediately after setData(json). Because of the way that React schedules state updates, data will not have the json content until after the component has rerendered.

    I think there’s two solutions here.

    1. Change allCategories so that the array comes from the json variable:
    const allCategories = ['all', ...new Set(json.map(item => item.category))]
    

    or

    1. Create a useEffect with data in the dependency array and only update the categories state when data changes:
     useEffect(() => {
       if (data) {
         setCategories(['all', ...new Set(data.map(item => item.category))]);
       }
     }, [data])
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search