Search code examples
javascriptreactjsreact-reduxredux-thunkredux-persist

How to implement remember me functionality in react js


I'm making a simple login signup form with remember me functionality in react js along with redux, thunk and redux-persist. When I send correct login details i.e. email and password the api returns a non changing (permanent) access_token.

Expected Functionality:- if remember me is ticked the access token should always be saved so that when ever I revisit the page after closing the browser or when I refresh the page I should be automatically logged in to home page

if remember me is not ticked the access token is stored only till I don't exit the page or I don't close the browser, once browser is closed the access_token is automatically deleted

my approach is:

if - remember me button is ticked then I want to persist the access token (received from api) in local storage

and if- remember me button is not ticked then I want to store the access token in session storage

can someone help me to implement this or correct my approach if it is wrong.

https://github.com/guneethind/login-signup

Login.js

>  const Login = () => {
>  const dispatch = useDispatch();
>  const navigate = useNavigate();
>
>  const data = useSelector((state) => state.login);
>
>  const onFinish = (values) => {
>    dispatch(setLoginValues(values));
>  };
>
>  useEffect(() => {
>    if (data?.loginSuccess?.access_token) {
>      message.success("Logged in");
>      navigate("/home");
>    } else if (data?.loginFailed?.status === 401) {
>      message.error(`${data.loginFailed.message}`);
>      navigate("/login");
>      dispatch(setLoginEmpty());
>    }
>  }, [data]);

store.js

import storage from "redux-persist/lib/storage";


const persistConsif = {
  key: "root",
  storage: storage,
};

const persistedReducer = persistReducer(persistConsif, reducers);

export const store = createStore(
  persistedReducer,
  composeWithDevTools(applyMiddleware(thunk))
);

export const persistor = persistStore(store);

index.js

ReactDOM.render(
  <Provider store={store}>
    <PersistGate loading={null} persistor={persistor}>
      <App />
    </PersistGate>
  </Provider>,
  document.getElementById("root")
);

Solution

  • Finally resolved the problem, I used cookies for when the remember me is unticked and local storage for when remember me is ticked

    here's the code for the same https://github.com/guneethind/login-signup/tree/cookies-implementaion