0

I have this function in ReactJS and I am trying to get the data from the API and assign it to an array.

const handleSearch = searchText => {
        let res = []
        let data = {}

        if (searchText.length > 3) {
            data = {
                address_str: searchText
            }
            SupportFormService.searchForAddress(userContextData.accessToken, data).then((response) => {
                let result = response.data.payload
                res = result.map(result => result.address)
                console.info(res) //1st console output
            }).catch((error) => {
                console.info(error)
            })
        } else {
            console.info('in else')
            res = []
        }

        console.info(res) //2nd console output
    }

When I do the 1st console, I am getting my data in an array as expected but the res variable outside of the if else block gives me an empty array.

  • Yes it basically does. But I achieved this by updating the state – Dakota Jhonson Aug 31 '20 at 17:19
  • State or no state, you must handle asynchronous code correctly. A promise represents a future result, and the `.then()` runs in the future - your other code continues before it runs, and you can't pull the values out of the future. See the dupe target for approaches to solve the problem. – Klaycon Aug 31 '20 at 17:24

0 Answers0