React Hook Async await how to hold rendering on a promise

Viewed 2981

I'm trying to fetch data while using async await but i'm getting errors when i'm trying to render. i assume is because i'm trying to render when it is in it's promise state.

The end game is trying to make this an action, i want to use this with React redux. But i wanted to start here first.

// App.js

import React, {useState, useEffect} from 'react';
import axios from "axios"

function App() {
    const [data, setData] = useState({});
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        async function fetchData() {
            const response = await axios(
                'http://lr.test/api/players',
            );
            console.log('data',response.data);

            setData(response.data);
            //setLoading(false) //i tried to set loading to false when it is ready but this doesn't work
            
        }

        fetchData()

    }, []);

    return (
           <ul>
                 {
                    data.map( (d) => {
                        console.log(d)
                        return (<li key={d.id}>{d}</li>)
                    })
                }
          </ul>
       )
          

//This give me error is not a function, so it's trying to render when it is a promise //how do i get around this? I tried checcking is array before rendering but that doesn't seem to work.

My console log is

{} //first empty object

{data: Array(4)}
data: (4) [{…}, {…}, {…}, {…}]
__proto__: Object
1 Answers

Instead of initializing data with an empty object

const [data, setData] = useState({});

initialize it with an empty array which has the map function:

const [data, setData] = useState([]);

This should make the initial render work.

By the way, if you are really logging response.data and the log shows an object containing yet another data property, you should use response.data.data instead.

Related