I have this function in react to fetch the data from my django api:
const [filterData, setFilterData] = useState([]);
const fetchFilterData = async () => {
const filter_url = 'http://127.0.0.1:8000/api/filters/'
try {
const response = await fetch(filter_url)
const result = await response.json();
setFilterData(result)
} catch (error) {
console.error('error fetching data: ', error);
}
}
and when I try to console.log the data it is show as undefined
at first but if I change something in the code (like add a white space or a new line) and save the fetched data appears and everything works fine but the issue is that I can’t render that data or pass it down as a prop to other components
here’s the react useEffect
hook:
useEffect(() => {
fetchData();
fetchFilterData();
}, []);
and I have tried logging the data in several ways but no use it always returns undefined
at first
here are several ways I have tried:
inside fetchFilterData
function:
if (filterData) {console.log(filterData.all_blocks) } else { console.log("this data is undefinde") }
*and this has return undefinde
as well and I still don’t know why *
passing it down as a prop to another component:
return (
{filterData && <DropDown items={filterData.all_blocks} /> }
);
I’m pretty new to react so any help would be appreciated 🙂
thank you guys in advance!!!