Home > Back-end >  setState doesnot change again once its set
setState doesnot change again once its set

Time:06-29

I am using Axios to post data to the server everything is working just fine but I wanted to show error message if email is already exists using a state hook but state does not change once its set can anyone help me what i am doing wrong

const [serverError, setServerError] = useState(false);
  const handleRegister = async ({ name, email, password }) => {
    const userdata = { name, email, password };
    const res = await apiUrl.post("/users", userdata);
    if (!res.statusText === "OK") return setServerError(true);
    setServerError(false);
    console.log(serverError);
    console.log(res.data);
    localStorage.setItem("token", res.headers["x-auth-token"]);
  };

CodePudding user response:

You need to use != operator to check for inequality.

if (res.statusText != "OK") return setServerError(true);

CodePudding user response:

The issue is here:

if (!res.statusText === "OK")

You have to use !== or != ( first one is equality check with datatype and second one is equality check. So the condition will be like:

if (res.statusText != "OK")
{
  return setServerError(true);
}

CodePudding user response:

I think you have error here

if (!res.statusText === "OK")

As you have defined a NOT operator before the variable it treats the variable to Boolean value that means Boolean === String => false always

Just keep

if (res.statusText === "OK")

And in case you want to check if there is value or not use in response.

if (res?.statusText === "OK")
  • Related