-3
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

asportnoy
  • 2,218
  • 2
  • 17
  • 31
khan
  • 3
  • 3
  • Does this answer your question? [The useState set method is not reflecting a change immediately](https://stackoverflow.com/questions/54069253/the-usestate-set-method-is-not-reflecting-a-change-immediately) – Phil Apr 16 '23 at 23:34

2 Answers2

0

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])
Tomr93
  • 36
  • 3
-1

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
   }, []);
Rohit Gupta
  • 4,022
  • 20
  • 31
  • 41
khan
  • 3
  • 3