Home > OS >  why do I get an empty prop when I console log?
why do I get an empty prop when I console log?

Time:07-06

can someone see why do I have selectionNames:[] empty when I console log ?? I've thought of using one sate i.e names instead of 2 i.e selectionNames and modifying name directly in my useEffect but it's not working. (I've copy and paste the logic of my function const init inside useEffect, but not working.

Can someone see where is the issue please ?

export default function Display() {
    const [names, setNames] = useState([])    
    useEffect(() => {
        axios.post("")
            .then(res => {
                console.log(res)
                setNames(res.data.names)
            })
            .catch(err => {
                console.log(err)
            })
    }, []);    
    const init = (e) => {
        return e.map((item) => {
            return {..item,types: item.types.map((t) => ({ ...t, selected: true }))
            };
        });
    };    
    const [selectionNames, setSelectionNames] = useState(init(names));
    console.log(selectionNames)
    ...
    const change = (id,item, value) => {setSelectionStandards((s) => s.map((item) => {...} return item;}));
    };

    return (
        <>     
          {selectionNames.map((item) => (...))}
            
        </>
    );
}

here is my json from my api:

{
    "names": [
        {
            "id": 1,
            "Description": "descr",
            "types": [
                {
                    "id": 1,
                    "decription":"descr1",
                },
                ...
        ]
        },
        ...
    ]
}

CodePudding user response:

This is what you should do:

import {useState, useEffect} from 'react';


const Display = () => {

    // The initial state is empty
    const [names, setNames] = useState([]);

    // This function will be called when component mounts
    const init = async () => {
        const {data} = axios.post('');
        setNames(data.names);
    
    }

    useEffect(() => {
        init();
    } , [])

    // First time, this will print an empty array.
    // After the initialization, you will get the actual names array
    console.log(names);
}

CodePudding user response:

import {useState, useEffect} from 'react';


const Display = () => {

    // The initial state is empty
    const [names, setNames] = useState([]);

    // This function will be called when component mounts
    const init = async () => {
        const { data } = await axios.post(''); // put the await before, call axios
        setNames(data.names);
    
    }

    useEffect(() => {
        init();
    } , [])

    // First time, this will print an empty array.
    // After the initialization, you will get the actual names array
    console.log(names);
}
  • Related