Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Reactjs array push not working in async function

 const [cart, setCart] = useState({})

    useEffect(()=>{
        const items = JSON.parse(localStorage.getItem('cart')); // return [5,6]
        let array = [];
        if(items && items.length){
            items.map(function (cart_id){
                getPack(cart_id).then((result)=>{
                    array.push(result.data) // not working
                    console.log(result.data) // got data as object!
                })
            })
            setCart(array);
            console.log(array); // return empty
        }
    }, []);

    const getPack = async(id) => {
        return await Api.Get('getPack', false, false, id); // get data from api
    }

What I trying to do is after get data from api from async function called getPack set it to object. I got data from getPack but I want to set it to array, I used array.push but it’s not working. Any idea what is wrong?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You return promise which is async, so your code console.log(array); will be executed before you get the response from your endpoint and entering inside callback in then. In other words, there is no guarantee that your code after getPack(cart_id).then will be execute when array is fields because it is asynchronous.

As an option create an additional state for your array instead of declaring it inside the useEffect:

const [array, setArray] = useState([])
useEffect(()=>{
    const items = JSON.parse(localStorage.getItem('cart')); // return [5,6]
    if(items && items.length){
        items.map(function (cart_id){
           getPack(cart_id).then((result)=>{
                setArray(oldArray => [...oldArray, result.data]) 
                console.log(result.data)
            })
        })
        console.log(array); // return empty
    }
}, []);

const getPack = async(id) => {
   return await Api.Get('getPack', false, false, id); // get data from api
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading