0
import React from "react";
import { Redirect, Route } from "react-router-dom";
import { useState, useEffect } from "react";
import To_Do_Lists from "./todo";

const ProtectedRoute = ({ component: Component, ...restOfProps }) => {
  const [isValidated, setIsValidated] = useState(false);

  let token = localStorage.getItem("Authorization");
  let config = {
    headers: {
      authorization: token,
    },
  };

  const checkAuth = async () => {
    await axios
      .get("http://localhost:3001/checkAuth", config)
      .then((res) => {
        if (res.status === 201) {
          console.log("res received", res);
          setIsValidated(true);
        }
        console.log(1, isValidated);
      })
      .catch((err) => console.log(err));
    console.log(2, isValidated);
  };
  useEffect(() => {
    checkAuth();
  }, []);

  return (
    <Route
      {...restOfProps}
      render={(props) =>
        isValidated ? <Component {...props} /> : <Redirect to="/" />
      }
    />
  );
};

export default ProtectedRoute;

When this component is used within react-router-dom, after i log in on the home page, it successfully makes a GET request. It even logs the "res received" inside the conditional IF statement. But it does not update the state variable via setIsValidated(true). Both console.log's (both 1 and 2) of the state variable, show it stays false. What am I missing here?

Stark
  • 11
  • 1
  • Duplicate: [Why calling react setState method doesn't mutate the state immediately?](https://stackoverflow.com/questions/30782948/why-calling-react-setstate-method-doesnt-mutate-the-state-immediately) –  Aug 31 '21 at 00:01

2 Answers2

0

You are combining async/await with .then. Just change the syntax to be without the '.then' callbacks:

const res = await axios.get("http://localhost:3001/checkAuth", config);
if (res.status === 201) ...
icostaykov
  • 21
  • 3
0

setState() does not mutate the state immediately.

setState() does not always immediately update the component. It may batch or defer the update until later. This makes reading this.state right after calling setState() a potential pitfall. Instead, use componentDidUpdate or a setState callback (setState(updater, callback)), either of which are guaranteed to fire after the update has been applied. If you need to set the state based on the previous state, read about the updater argument below.

Hence when you are at console.logs it is not guaranteed that the state has been mutated. If you want to make sure you call after the mutation you can use the setState callback.

Janitha Tennakoon
  • 856
  • 11
  • 40