简体   繁体   中英

useState not updating properly with axios and Promise

I have this code:

  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState(false);
  const [loading, setLoading] = useState(false);
  const [success, setSuccess] = useState(false);

  const onSubmitHandler = (event) => {
    event.preventDefault();
    setLoading(true);
    axios({
      method: 'post',
      url: `${process.env.REACT_APP_API_URL}users/auth/sign_in`,
      data: { email, password },
      headers: { 'content-type': 'application/json' },
    })
      .then(function (response) {
        setSuccess(true);
        console.log(response, ' sucesso');
        const authData = {
          accessToken: response.headers['access-token'],
          client: response.headers.client,
          uid: response.headers.uid,
        };
        localStorage.setItem('authData', JSON.stringify(authData));
      })
      .catch(function (error) {
        setLoading(false);
        setError(true);
        console.log(error, 'error');
      });
  };

if(success) return <Redirect to="/" />

It is a login page and this function gets executed when the user press the Login button. It works just fine but I'm having some trouble to make it redirect to the main page.

I have added a success const as useState and everytime the request is successful, it was supposed to set success to true with setSuccess(true) and redirect the user to / using react-router-dom but it is not working. The state still as false. What I'm doing wrong?

I have also tried using useEffect like this:

  const returnFunc = () => <Redirect to="/" />;
  useEffect(() => {
    if (success) {
      returnFunc();
    }
  }, [success, loading]);

I think you should just do:

useEffect(() => {}, [success, loading]);

if(success) return <Redirect to="/" />

If you are calling your returnFunc() in the UseState it is not going to work, just with nothing inside the UseEffect but only [success] is going to re-render the page because you set success to true and then it should take you to the main page.

你能试试这个吗

return success ? <Redirect to="/" /> : "Render somthing for none login state";
...
import { BrowserRouter as Router } from "react-router-dom";

...
return (
  ...
  <Router>
   {success && <Redirect to="/" />}
  </Router>
)



// or you can try this way
import { useHistory } from "react-router-dom";

let history = useHistory();
...

useEffect(() => {
    if (success) {
      setSuccess(false)
      history.push('/');
    }
  }, [success]);

Fixed adding window.location.href = '/'; to the .then and added an if to check if there is localStorage.

  if (localStorage.getItem('authData')) {
    return <Redirect to="/" />;
  }

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