0

I'm setting state for start and end date of checkin and checkout date. I got validDateRange which is an array of valid date and length. Try to set the state of total to the length of array multiply with the price of the room but somehow react not updating my total state. The log of totalCost is totally true


const RoomDetails = (props) => {
    const roomDetails = props.location.state;

    const [startDate, setStartDate] = useState();
    const [startEnd, setEndDate] = useState();
    const [total, setTotal] = useState();


    const handleOnSelectCalendar = (startDate, endDate, validDateRange) => {
        // console.log(startDate, endDate, validDateRange.length);
        setStartDate(startDate);
        setEndDate(endDate);
        // console.log(roomDetails.price, validDateRange.length);
        // var totalCost = roomDetails.price * validDateRange.length;
        setTotal(roomDetails.price * validDateRange.length);
        console.log(startDate, endDate, total); // output: 2020-12-08 2020-12-11 undefined
    };
    return (...);
}

2
  • Does this answer your question? React setState not updating state Commented Dec 8, 2020 at 7:30
  • It's seems like it does update my state. But it update async after my console.log so i wouldn't see that right away. I need to use useEffect to see the result and passing total to the params to log when total is change. This is in my head right now. isThis === true? Commented Dec 8, 2020 at 8:35

1 Answer 1

2

setState is asynchronous. Console logging synchronously right after setting state to see what that state looks like afterwards will most likely not reflect a correct value. If you want to see the value when total changes, try something like this:

useEffect(() => {
  console.log(total);
}, [total]);
Sign up to request clarification or add additional context in comments.

1 Comment

nice! I didn't know that. Thanks for your help sir Cory

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.