Reputation: 79
I have problem with mapping fetched data in react. I have these data, which I successfully fetch, but I have trouble, with mapping it to array.
order_id: 9999,
order_items: [
{
ean: 1234,
name: 'LIV Aquafilter 2000',
count: 1
},
{
ean: 12345,
name: 'Beko EWUE 7612CSXS0',
count: 1
}
]
There is my code, the data console log work perfectly, but another two just logs nothing
const fetchInvoiceData = useCallback(async () => {
setIsLoading(true);
setError(null);
try {
const response = await fetch("some_link");
if (!response.ok) {
throw new Error("error!");
}
const data = await response.json();
console.log(data);
const transformedData = data.results.map((invoiceData) => {
return {
id: invoiceData.order_id,
name: invoiceData.name,
};
});
setListData(transformedData);
console.log(listData);
console.log(transformedData);
} catch (error) {
setError(error.message);
}
setIsLoading(false);
}, []);
useEffect(() => {
fetchInvoiceData();
}, [fetchInvoiceData]);
Upvotes: 2
Views: 92
Reputation: 17858
The reason for the console.log(listData)
logs nothing is setting the state is asynchronous.
And the reason the console.log(transformedData);
logs nothing is because you need to use data.order_items.map
instead of data.results.map
Upvotes: 1