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 (...);
}

Gr4y
  • 170
  • 2
  • 10
  • Does this answer your question? [React setState not updating state](https://stackoverflow.com/questions/41446560/react-setstate-not-updating-state) – Sarun UK Dec 08 '20 at 07: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? – Gr4y Dec 08 '20 at 08:35

1 Answers1

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]);
Cory Harper
  • 1,023
  • 6
  • 14