简体   繁体   中英

setState doesnot change again once its set

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"]);
  };

您需要使用!=运算符来检查不等式。

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

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);
}

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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM