Home > Back-end >  How to setState with value returned by an async function
How to setState with value returned by an async function

Time:08-30

I am attempting to setState (adding an element to an array) following an async function call. However images is set with undefined. (Even though underlying function definitely returns with a value.)

How do I make sure my array is updated with value after return from async function concludes?

const [images, setImages] = useState([])
pickerResult.map(async (img) => {
    await handleImageUpload(img.uri)
    .then((url) => {
    setImages(images => [...images, url]);
    })               
})
useEffect(() => {
        console.log(images)
    }, [images])
Array [
  undefined,
  undefined,
]

CodePudding user response:

Try this:

const [images, setImages] = useState([])
pickerResult.map(async (img) => {
    const url = await handleImageUpload(img.uri)
    setImages(images => [...images, url]);              
})
  • Related