2

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]);
Racer Bubu
  • 79
  • 7
  • What's `listData`? Are you trying to `console.log` a variable that doesn't exist? Although I see you're also mapping over `.results` even though your JSON only has `.order_items`? – Kelvin Schoofs Jul 23 '21 at 18:59
  • Does this answer your question? [Why calling react setState method doesn't mutate the state immediately?](https://stackoverflow.com/questions/30782948/why-calling-react-setstate-method-doesnt-mutate-the-state-immediately) – pilchard Jul 23 '21 at 19:02
  • @KelvinSchoofs listData is just useState array, the .results was the problem, thank you. – Racer Bubu Jul 23 '21 at 19:15

1 Answers1

1

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

SuleymanSah
  • 17,153
  • 5
  • 33
  • 54