简体   繁体   中英

React useState not updating value in async function

const Login = () => {
  const [data, setData] = useState({
    name: "",
    email: "",
    password: ""
  });
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState(""); // set empty error state

  const handleChange = event =>
    setData({ ...data, [event.target.name]: event.target.value });

  const handleSubmit = async event => { // async function to handle submit
    event.preventDefault();

    try {
      setIsLoading(true);

      const response = await axios.post( // response from server
        "http://localhost:5000/api/users/signup",
        JSON.stringify(data),
        {
          headers: {
            "Content-Type": "application/json"
          }
        }
      );
      console.log(response.data); // data comes back fine
      setIsLoading(false);
    } catch (err) {
      const message = err.response.data.message;
      setError(message); // set error message if there is an error
      setIsLoading(false); // always successfully setLoading to false
      console.log(isLoading); // result is false
      console.log(message); // result message
      console.log(error); // result is still empty string. state never updated with message
    }
  };

I cant seem to figure out why the error state is not updating in the catch block. I alwasy receive a message and can log the message but the state never updates to the message. I noticed if I submit the form multiple times on the second submit the state will update.

Any help is appreciated.

For any side-effect , like network call, data update which is async in nature. You have to use useEffect . This will solve the issue. To reuse the logic, You can create custom hooks . See the example: Custom-Hooks

Use Effect:

useEffect(
  () => {
    const subscription = props.source.subscribe();
    return () => {
      subscription.unsubscribe();
    };
  },
  [props.source],
);

Custom Hook:

function FriendStatus(props) {
  const [isOnline, setIsOnline] = useState(null);

  useEffect(() => {
    function handleStatusChange(status) {
      setIsOnline(status.isOnline);
    }

    ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
    return () => {
      ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
    };
  });

  if (isOnline === null) {
    return 'Loading...';
  }
  return isOnline ? 'Online' : 'Offline';
}

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