Search code examples
reactjsuse-effectuse-statestrapi

useState returning empty array


I have this very simple code

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

import api from "../assets/services/api.js";

const Teste = () => {
    const [searchBand, setSearchBand] = useState("");
    const [bands, setBands] = useState([]);
    useEffect(() => {
        const loadBands = async () => {
            const response = await api.get();
            setBands(response.data);
            console.log(response.data);
            console.log(bands);
        };
        loadBands();
    }, []);

that fetches data from Strapi. Thing is: bands only returns an empty array and I need that data to be mapped, so I can display it.

Here is the image:

console image

What am I doing wrong?

Thanks in advance.


Solution

  • Because state only render when component re-render. So put console.log(bands); outside the useEffect to see the new value when the component render

    useEffect(() => {
        const loadBands = async () => {
            const response = await api.get();
            setBands(response.data);
            console.log(response.data);
        };
        loadBands();
    }, []);
    
    console.log(bands);