sam
sam

Reputation: 125

How to use the useDispatch() hook inside the useEffect() hook?

I am using the useEffect() hook in my functional App component to check if the authentication has expired, so that I can dispatch an action to delete the persisted authentication state (using redux-persist). below is the code:

import React, { useEffect } from "react";
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
import { useDispatch, useSelector } from "react-redux";
import { signout } from "./app/state/authSlice";

import Signin from "./app/pages/Signin";
import Landing from "./app/pages/Landing";

const App = (props) => {
  const dispatch = useDispatch();
  const auth = useSelector((state) => state.auth);
  const expired = new Date(Date.now()) >= new Date(auth.expires);
  useEffect(() => {
    const main = () => {
      if (expired) {
        console.log("Auth expired.");
        dispatch(signout);
      }
    };
    main();
  }, [dispatch, expired]);

  return (
    <Router>
      <Switch>
        <Route exact path="/" {...props} component={Landing} />
        <Route exact path="/signin" {...props} component={Signin} />
      </Switch>
    </Router>
  );
};

export default App;

Now, I am getting the Auth expired console log when the expiry time is past, but the dispatch is not happening and my state still persists after the expiry time. I know that the signout action is correctly configured because I am using that in another component onClick.

Upvotes: 0

Views: 51

Answers (1)

sam
sam

Reputation: 125

This was just a typo. I forgot to call the signout() action creator.

Correct code below.

import React, { useEffect } from "react";
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
import { useDispatch, useSelector } from "react-redux";
import { signout } from "./app/state/authSlice";

import SigninPage from "./app/pages/Signin";
import LandingPage from "./app/pages/Landing";

const App = (props) => {
  const dispatch = useDispatch();
  const auth = useSelector((state) => state.auth);
  const expired = new Date(Date.now()) >= new Date(auth.expires);
  useEffect(() => {
    const main = () => {
      if (expired) {
        console.log("Auth expired.");
        dispatch(signout());
      }
    };
    main();
  }, [dispatch, expired]);

  return (
    <Router>
      <Switch>
        <Route exact path="/" {...props} component={LandingPage} />
        <Route exact path="/signin" {...props} component={SigninPage} />
      </Switch>
    </Router>
  );
};

export default App;

Upvotes: 1

Related Questions