简体   繁体   中英

How to store user logged in state with React Redux

I have an application which uses Google OAuth 2.0 to sign in a user. However, I'm unsure what the best way of storing that the user is logged in, using Redux.

What I'm wondering is if using useEffect in App.js is the Redux-way of checking that a user is logged in? It feels a bit unnecessary to have an useEffect in the App.js file which constantly will check if the user is signed in, instead of just keeping that state.

Or maybe it's more secure to do it like this constantly and it's actually good practise?

I'm very curios of hearing your options on this.

Here is my idea of doing it. It works, but as I mentioned I'm not sure this is the optimal way of doing it:

App.js

const App = ({ oauthLogin }) => {
  useEffect(() => {
// this will simply get the user if already logged in through looking at req.body in server
// and set it in SIGN_IN. If not logged in 
    oauthLogin(); 
  }, [oauthLogin]);

  return (
    <div>
      <BrowserRouter>
        <Navbar />
        <div className="default-container">
          <div className="page-container">
            <Routes>
              <Route path="/posts" exact element={<Posts />} />
              <Route path="/login" exact element={<Login />} />
              <Route path="/sign-up" exact element={<SignUp />} />
            </Routes>
          </div>
        </div>
      </BrowserRouter>
    </div>
  );
};

export default connect(null, { oauthLogin })(App);

index.js

import { Provider } from "react-redux";
import { createStore, applyMiddleware, compose } from "redux";
import thunk from "redux-thunk";

import App from "./App";
import reducers from "./reducers";

const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(reducers, composeEnhancers(applyMiddleware(thunk)));

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.querySelector("#root")
);

authReducer.js

import { SIGN_IN, SIGN_OUT } from "../actions/types";

const INITIAL_STATE = {
  isSignedIn: null,
  userId: null,
};

const authReducer = (state = INITIAL_STATE, action) => {
  switch (action.type) {
    case SIGN_IN:
      return { ...state, isSignedIn: true, userId: action.payload };
    case SIGN_OUT:
      return { ...state, isSignedIn: false, userId: null };
    default:
      return state;
  }
};

export default authReducer;

you can use useSelector from react-redux to read the state from redux and check if the user is logged in like:

  const isUserSignedIn = useSelector((state) => state.auth.isSignedIn)

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