0

I want to console log the value of a variable belonging to the component inside useState, but it keeps console logging 'null' right after I set it. Is there like a "getState"-function? Before upgrading to latest react with hooks I could access the variables with this.state.variableName.

Thanks a lot guys!

const DriverHome = (props) => {
const [bookings, setBookings] = useState([]);

useEffect(() => {
if (!user) {
  props.history.push('/login');
}

socket.on('booking updated', (message, booking) => {
  getAllDriverBookings(user.email)
    .then((b) => {
      setBookings(b.data.bookings);
      playSound();
    })
    .then(console.log('bookings:', bookings));
});

When i try to print bookings, it keeps printing null even though it's not.

skyboyer
  • 22,209
  • 7
  • 57
  • 64
lunarkakka
  • 55
  • 2
  • 7
  • Would you mind providing some code of what you tried? – Rallen May 06 '19 at 18:06
  • I just updated the question, thanks – lunarkakka May 06 '19 at 18:09
  • The bookings variable is definitely not null, I'm rendering some components using it's data before the socket being triggered – lunarkakka May 06 '19 at 18:10
  • Well, State update in react is async. So, the console statement is possibly executed before the state is actually updated. Try checking the value inside useEffect() – Deepak May 06 '19 at 18:35
  • try updating the state after spreading prevState: `setBookings((prevState) => ([ ...prevState, ...b.data.bookings ]))` – humanbean May 06 '19 at 19:20
  • Possible duplicate of [Referencing outdated state in React useEffect hook](https://stackoverflow.com/questions/53633698/referencing-outdated-state-in-react-useeffect-hook) – Aprillion Nov 15 '19 at 11:28

0 Answers0