guanacone / fullstack_app

BSD Zero Clause License
0 stars 0 forks source link

redirect on successful login #29

Closed guanacone closed 3 years ago

guanacone commented 3 years ago

The issue is that after successful login the user gets redirected to /user as expected but with a 401 error. Only when the page is refreshed it shows the user index. I suspect that it is because of some delay when writing or retrieving the token from local Storage.

Tried to modifie the useFetchAPI() hook as following to await that the token is retrieved from localSorage but without success.

const useFetchAPI = ({ endpoint }) => {
  const [data, setData] = useState(null);
  const [error, setError] = useState(null);

  useEffect(() => {
    (async () => {
      try {
        const authUser = await JSON.parse(window.localStorage.getItem('gatsbyUser'));
        const result = await axios({
          url: endpoint,
          headers: { Authorization: `Bearer ${authUser.token}` },
        });
        setData(result.data);
      } catch (err) {
        setError(err);
      }
    })();
  }, []);
  return { data, error };
};

Maybe that I have to await for the token to be written to localStorage but not sure where this should happen. Any hints?

edwmurph commented 3 years ago

you're theory might be right but the way you tried to wait for the item in local storage won't work

        const authUser = await JSON.parse(window.localStorage.getItem('gatsbyUser'));

JSON.parse and localStorage.getItem are both synchronous APIs so await'ing them doesn't do anything

technically you could asynchronously poll localstorage in a loop until it has the value you're looking for but that strikes me as a hack and ideally theres a simpler way

guanacone commented 3 years ago

The solution was to await handleLogin() in src/login.js

const handleSubmit = async (evt, { email, password }) => {
  evt.preventDefault();
  await handleLogin({ email, password });
  return isLoggedIn() ? navigate('/user') : alert('wrong email/password');
};