I have a state called allDatas in react js, where there are data such as photos and text in the form of objects, and I get the page ID from the params, and now, using the filter() method, I asked that the object whose ID matches the ID params is equal to get its data and save it in another state, but it does not give me the data and gives me an empty array, where is the problem? thank you
my code :
let params = useParams()
const [allDatas, setAllDatas] = useState(AllCoursesData)
const [buyData, setBuyData] = useState([])
useEffect(() => {
const filterData = allDatas.filter(data => data.id === params)
if (filterData.length > 0) {
setBuyData(filterData)
}
console.log(filterData);
}, [params])
Arvin is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
2
You’re getting an empty array returned from the filter()
method because you’re matching data.id
with params
instead of params.id
. The useParams()
hook returns an object. You should refactor your code as follows:
let params = useParams()
const [allDatas, setAllDatas] = useState(AllCoursesData)
const [buyData, setBuyData] = useState([]);
useEffect(() => {
const filterData = allDatas.filter(data => data.id === params.id);
if (filterData.length > 0) {
setBuyData(filterData)
}
}, [params.id])
This should solve your issue.