redux-persist
redux-persist copied to clipboard
Conditionally persist store if "Keep Me Logged In" is checked?
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.
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
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)
@priyesh9875 That's the solution I ended up going for.
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 what if someone refreshes? If rememberMe is false and user refreshes, data should be persisted,right?
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>
);
}