Normally data fetch is good but when category data find and so filter method then get data is undefined. I think my data fetch is not right!
import { useEffect, useState } from "react";
const PostDataLoad = () => {
const [postData, setPostdata]=useState([])
useEffect(()=>{
fetch('/public/PostDatas.json')
.then(res=> res.json())
.then(data=>{
console.log(data);
setPostdata(data)
})
},[])
const Category1 = postData.filter(findCategory=> findCategory.category === 'Technology')
return [postData,Category1]
};
export default PostDataLoad;
I want to get data load in filter method.
2
Answers
Category1
will not be updated when you fetch the data, since there’s nothing changing it.My suggestion is move the filter part elsewhere, so that your
PostDataLoad
will only need to responsible for 1 thing (fetching data).Assuming that the exported
PostDataLoad
function is a hook, there are a few things that you need to fix:use
Category1
will only be computed once (the initial call) and will not be recomputed. Move the logic of calculating the return value inside theuseEffect()
‘s fetch call: