DEV Community

marcosdipaolo
marcosdipaolo

Posted on

useState hook variable's value is always one step behind

Here using React and Next.js.

Here a summary of the code:

I have this hook:

import { useState } from 'react';
import BigCalendar from 'react-big-calendar'
import moment from 'moment';
import CreateEventForm from './CreateEventForm';

const localizer = BigCalendar.momentLocalizer(moment);

const Calendar = props => {

    const [newEvent, setNewEvent] = useState({
        start: new Date(),
        end: new Date(),
    });

    const onSelectHandler = info => {
        // logging the new info
        console.warn('New info: ', info);
        // assigning the new info to the hooks variable
        setNewEvent(info);
        // logging the hook variable's value 
        console.warn('Hook variable\'s value: ', newEvent);
    }

}

There's actually nothing else to be told, when the handler is fired by an event, the variable info comes with an object on new information. Inmediately I log the information to the console to see that it is actually the correct and new info, i set the info to the hook's variable and inmediately log to the console the value of the hook's variable and it doesn't match the new info i just tried to assign to it. It's actually logs the default values (the 2 dates).
If I do it again, it happens the same but the hooks variable this time doesn't log the default, but the new info of the first try, so basically it's coming one time late every time.

What could i have done to make this happen?

The event firing the handler is when i select a slot at the React Big Calendar

const myEvents = props.events.map(event => {
    return {
        ...event,
        start: new Date(event.start),
        end: new Date(event.end)
    };
});

    <BigCalendar
        defaultView="week"
        localizer={localizer}
        events={myEvents}
        startAccessor="start"
        endAccessor="end"
        selectable={true}
        onSelectSlot={onSelectHandler}
    />

Top comments (0)