简体   繁体   中英

How to update react state in useState hook?

I am trying to set the error message in the state. I am using react hooks for storing error message. I don't know but it is not updating.

Here is my code,

const [code, setCode] = useState("");
const [codeError, setCodeError] = useState("");


.catch((error) => {
    console.log("code error", error.message, typeof error.message);
    setCodeError(error.message);
    setCode("");
    setProcessing(false);
  });

This is not updating the state. But it is logging the error with a type of string.

I even tried to check if the state updated using useEffect hook but it is not even logging in the useEffect hook.

Here is how you can do this ->

I want to clear the code everytime there is an error.

useEffect(() => {
  if (codeError && code) {
    setCode("")
  }
}, [codeError])

The code is correct so I would assume you are not checking the value after setting the data.

It would be better if you put the whole component here or on any code hosting site.

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