3

I want to send user to backend in function handleJoin(). After setUser is called, the initial data not changed.

How to fix it without using class

App.js

import React, { useState } from "react";
import Join from "./components/Join";

const App = () => {
  const [user, setUser] = useState({ });

  // Send user data to backend
  const handleJoin = (input) => {     
    console.log(input);               // >   {name: "myname"}

    setUser(input);                   //     Not working!

    console.log(user);                // >   { }

    // I want to connect backend here
    // But the user objet is empty
  };

  return <Join onJoin={handleJoin} />;
};

export default App;

1
  • How can we answer this without seeing what the Join component does, and in particular how its onJoin prop is used? Commented Apr 10, 2020 at 17:06

2 Answers 2

4

user will be updated on the next render after calling setUser.

import React, { useState, useEffect } from "react";
import Join from "./components/Join";

const App = () => {
  const [user, setUser] = useState(null);

  // This is a side effect that will occur when `user`
  // changes (and on initial render). The effect depends
  // `user` and will run every time `user` changes.
  useEffect(() => {
    if (user) {
      // Connect to backend here
    }
  }, [user])

  // Send user data to backend
  const handleJoin = (input) => {     
    console.log(input);
    setUser(input);
  };

  return <Join onJoin={handleJoin} />;
};

export default App;
Sign up to request clarification or add additional context in comments.

Comments

2

State update is not synchronous so it will not update user object right away but it will be updated asynchronously. So Either you can use input which is going to be user value to be sent to backend or you can use useEffect() hook which will be triggered when user value will be udpated

useEffect(() => {
  // this will be triggered whenever user will be updated
  console.log('updated user', user);
  if (user) {
    // connect to backend now
  }
}, [user]);

4 Comments

user will initially be truthy since its initial value is {}.
it conveys the idea
When I try this, the code inside the useEffect runs endlessly.
There must be updating/setting user value inside that useEffect which is causing cyclic rerender since useEffect has user dependency and it will run whenever user will change

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.