0

so I'm trying to post data to the server and get a response in return. somehow the API response change randomly Idk why, maybe you guys have any clue...

this is my code -

const [message, setMessage] = useState(false);
const [data, setData] = useState({
  firstName: "",
  lastName: "",
  userName: "",
  email: "",
  password: "",
});
const [errorMessage, setErrorMessage] = useState(false);

const handleSubmit = (event) => {
event.preventDefault();
axios
  .post("/register", {
    fullname: data.firstName + " " + data.lastName,
    username: data.userName,
    email: data.email,
    password: data.password,
  })
  .then((res) => {
    console.log(res);
    setMessage(res.data.success);
    console.log(message);
    if (message) {
      console.log("success");
    } else {
      console.log("error");
    }
  });
};

const handleChange = (event) => {
  setMessage(false);
  setErrorMessage(false);
  const newData = { ...data };
  newData[event.target.id] = event.target.value;
  setData(newData);
};

I have no clue what is causing this issue...

enter image description here

so the first time I get false, and then all the other calls are true, although I have a unique property for this property in my schema. sometimes it starts with false and then true and then all false.

second scenario

enter image description here

any idea guys? thanks for your help.

  • Does this answer your question? [The useState set method is not reflecting a change immediately](https://stackoverflow.com/questions/54069253/the-usestate-set-method-is-not-reflecting-a-change-immediately) – David Aug 19 '22 at 13:10
  • `console.log(message);` is showing you the *current* state, which is: `const [message, setMessage] = useState(false);` There's no error, just an incorrect expectation of state updates. – David Aug 19 '22 at 13:10
  • thank you guys for your help, so david any idea how i should change it? – Yarden Yosef Aug 19 '22 at 13:11
  • Sure, the value you want at that time is in `res.data.success`, not `message`. – David Aug 19 '22 at 13:12

1 Answers1

0

If I understood correctly your code, the variable message is boolean. Basically, the setMessage() effect is not immediate but it is delayed. In order to overcome the problem you have to use useEffect() to capture the change.

You can do something like this:

axios
    .post("/register", {
        fullname: data.firstName + " " + data.lastName,
        username: data.userName,
        email: data.email,
        password: data.password,
    }).then((res) => {
        console.log(res);
        setMessage(res.data.success);
    });

useEffect(() => {
    if (message) {
        console.log("success");
    } else {
        console.log("error");
    }
}, [message])
Andrea Cola
  • 127
  • 1
  • 8