Skip to content
Advertisement

setState for react function component not updated my state

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

Advertisement

Answer

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]);
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement