简体   繁体   中英

Updating useState variable after calling async function

I have a function that calls an API like this:

static async getReport(date) {
    const url = reportUrl + date
    const method = 'GET'
    try {
        return await axios({
            url,
            method: method,
            responseType: 'blob'
        })
    } catch (error) {
        return error
    }
}

Than in my component I use this function like this:

async function handleClick() {
    const response = await ReportService.getData(date)
    if (response instanceof AxiosError) {
        setSuccess(false)
        handleClickSuccess()
    } else {
        setData(response)
        drawTable()
    }
}

'setSuccess' and 'handleClickSuccess' functions don't really matter, but in case of successful call to an api I set data from response to 'setData' function which is 'useState' hook. Than I call function 'drawTable' which draws a table based on the state of 'setData' hook. The problem is that by the moment 'drawTable' function is called 'setData' hook is not yet filled with data from call to my api. How do I fix this?

I tried other topics here but they don't seem to help me, correct me If that's not true

As you know that set functions of useState hook take some time to update the state. Here instead of calling this drawtable function inside async function add a useEffect and add dependency of the data.

const [data,setData] = useState([]);

useEffect(()=>{
if(data.length > 0){
drawTable();
}
},[data,drawTable])

this will fix the asynchronus flow error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM