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
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
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 aftersetData(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.
or
data
in the dependency array and only update the categories state when data changes: