Home > Back-end >  is there any way to usestate respond immediately?
is there any way to usestate respond immediately?

Time:03-06

I was wanting to get value from the my server of the node with the usestate, but it returns the empty array value first and then pops up the value of my axios

has any way of the value of the axios appears first than that of the empty array ?

my code:

const [valTop, valTopstate] = useState([])

    async function MusicTop() {
        axios("http://localhost:3001/")
        .then(res=>{
            valTopstate(res.data.tracks.data)
        })
    }
    
    useEffect(()=>{
        MusicTop()

    }, [valTop])

CodePudding user response:

Your code is fine but UseEffect is executed only after the component is rendered, so you can apply a logic that is the array is empty then show the loader and if not show the array values, and if this is your child component what you can do is that when this child component is going to be executed then you can first fetch the required array value by calling a function in the parent component and pass the values as props in the child component.

  • Related