schroed
schroed

Reputation: 23

How to setState with value returned by an async function

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,
]

Upvotes: 2

Views: 1059

Answers (1)

Sanket Shah
Sanket Shah

Reputation: 3091

Try this:

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

Upvotes: 1

Related Questions