redux-persist icon indicating copy to clipboard operation
redux-persist copied to clipboard

Conditionally persist store if "Keep Me Logged In" is checked?

Open ghost opened this issue 8 years ago • 6 comments

How would I implement a "remember me" checkbox like every login has, with redux-persist?

My problem is that we must call persistStore(store) before the store is created, but I'd need it to be conditionally applied with the login action.

ghost avatar Jan 15 '17 05:01 ghost

One way is to create two reducers, say A(remember me) and B(temp). If remember me is selected, then dispatch actions of reducer A, else dispatch actions of reducer B.

Also mention reducer B as blacklist in store config, so that it wont be persisted

priyesh9875 avatar Jan 15 '17 17:01 priyesh9875

Another option is to use the pause method of the persistor. Or you can use the value of remember me to decide whether or not to accept the rehydrate payload (using custom rehydration, not autoRehydrate)

rt2zz avatar Feb 07 '17 05:02 rt2zz

@priyesh9875 That's the solution I ended up going for.

dwjohnston avatar Oct 16 '18 00:10 dwjohnston

A use that and it work fine

App.js

  componentDidMount() {
    window.addEventListener('beforeunload', ev => {
      ev.preventDefault();
      const { auth, signOut } = this.props;
      if (!auth.rememberMe) {
        signOut();
      }
    });
  }

Eth3rnit3 avatar Sep 23 '19 09:09 Eth3rnit3

@Eth3rnit3 what if someone refreshes? If rememberMe is false and user refreshes, data should be persisted,right?

keshav263 avatar Sep 23 '21 11:09 keshav263

try this package "react-beforeunload":

import React from "react";
import { Beforeunload } from "react-beforeunload";
import { logout } from "state/auth/slice";
import { useAppSelector, useAppDispatch } from "hooks";
import LayoutWrapper from "./styles";

export default function Layout({ children }: { children: React.ReactNode }) {
  const dispatch = useAppDispatch();
  const {
    auth: { rememberMe },
  } = useAppSelector((state) => state);

  return (
    <Beforeunload
      onBeforeunload={() => {
        if (!rememberMe) {
          dispatch(logout());
        }
      }}
    >
      <LayoutWrapper data-testid="app-layout">
        <main className="content">
          {children}
        </main>
      </LayoutWrapper>
    </Beforeunload>
  );
}

MohammedYoussefSoliman avatar Oct 17 '22 18:10 MohammedYoussefSoliman