'How to pass data to React Hook

I am new to React and I try to implement following code where I get axios response:

response.data

returns expected array. But when I try to use 'setRankings' setter to put data into 'rankings' array it is empty (undefined in console)

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


const Rankings = () => {

    const [rankings, setRankings] = React.useState([])

    useEffect( () => {
        (
            async () => {

                const response = await axios.get('rankings')
                //console.log(response.data) // returns expected data
                const x = setRankings((response.data))
                console.log(x)  // returns undefined
                //console.log(rankings) // also empty array. why?
            }

        )();

    }, []);



    return (
        .....
            
    );
};

export default Rankings;

What am I doing wrong?



Solution 1:[1]

You need to detect when a change happens to your state. Add a new useEffect like this:

useEffect(() => {
  console.log(rankings)
}, [rankings]) # It'll be called when rankings get updated

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mohammad Tbeishat