Search code examples
reactjsasync-awaituse-effectuse-state

How to async fetch data in useEffect


I have some issue. When I do to async fetch data (using axios for fetching) in the useEffect, and after I set responsed data to state, using a useState hook. And page render befor then I got response from server. For demonstration this issue I have putted console.log for get current state, and I get 'undefined':

const [positions, setPositions] = useState([]);

useEffect(() => {
    const fetchPositions = async () => {
        const response = await EmployeeService.getEmployeePositions();
        setPositions(response.data);
    };
    
    fetchPositions();
    console.log('positions from state: ', positions); //undefined
}, []);

Method for fetching data from "EmployeeService":

getEmployeePositions(){
    return axios.get(EMPLOYEE_API_BASE_URL + '/positions');
}

Thanks in advance, and best regards!


Solution

  • React needs to re-render to display the results. Which means you need to capture the result on the subsequent re-render that is caused when you setState. Move the console log outside of the useEffect

    const [positions, setPositions] = useState([]);
    
    useEffect(() => {
        const fetchPositions = async () => {
            const response = await EmployeeService.getEmployeePositions();
            setPositions(response.data);
        };
    
        fetchPositions();
    }, []);
    
    console.log('positions from state: ', positions); // NOT UNDEFINED
    

    React will always render once before you have data. So you can catch it with a condition.

    if (positions.length === 0) {
       return null;
    }