简体   繁体   中英

using updated state in function

I have a function called confirmOrder that takes in orderData and makes an API call with that data:

const confirmOrder = () => {
    // updateTime();
    updateDate();
    // delete this
    console.log(`order data: ${JSON.stringify(orderData)}`);
    axiosWithAuth()
        .post(`/diner/${props.account.id}/confirm-order`, orderData)
        .then(res => {
            console.log(res);
        })
        .catch(err => console.log(err));
}

The orderData object has properties for both date and time :

const [orderData, setOrderData] = useState({
    date:'',
    time: '',
    truck_id: props.selectedTruck.id,
    breakdown: props.order,
    subtotal: orderSubtotal,
    tip: tipVal.tip,
    total: orderSubtotal + Number(tipVal.tip)
})

As you can see, when I run confirmOrder (through an onClick), a call is made inside that function (ie updateDate ) that should update the values of orderData.date and orderData.time . Here is the code for that:

    const updateDate = () => {
        let date = new Date();
        let month = date.getMonth() + 1;
        if (month < 10) {
            month = '0' + month;
        };
        let calenDay = date.getDate();
        if (calenDay < 10) {
            calenDay = '0' + calenDay;
          };
        setOrderData({
            ...orderData,
            date: `${date.getFullYear()}-${month}-${calenDay}`,
            time: `${date.getHours()}:${date.getMinutes()}`
        });
    }

The problem I'm having is when I make the API call inside of confirmOrder , orderData.date and orderData.time are being sent to the backend as empty strings instead of with the updated code. How can I resolve this problem?

In React, setting state is asynchronous . When you call the state updater, all you do is schedule an update and rerender. The rest of your function will finish running and then the state will be updated and your component rerendered.

If your UI does not depend on the date and time strings, they should not be included in the state at all. You should generate those strings and then combine them with the state to send the request.

const updateDate = () => {
    let date = new Date();
    let month = date.getMonth() + 1;
    if (month < 10) {
        month = '0' + month;
    };
    let calenDay = date.getDate();
    if (calenDay < 10) {
        calenDay = '0' + calenDay;
    }
    return ({
        date: `${date.getFullYear()}-${month}-${calenDay}`,
        time: `${date.getHours()}:${date.getMinutes()}`
    });
}

const confirmOrder = () => {
    const date = updateDate();
    axiosWithAuth()
        .post(`/diner/${props.account.id}/confirm-order`, { ...date, ...orderData })
        .then(res => {
            console.log(res);
        })
        .catch(err => console.log(err));
}

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