Skip to content

Instantly share code, notes, and snippets.

@sidharrth2002
Created December 19, 2021 15:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sidharrth2002/5bd04e5bb0d8f6a3cbf42cbdeb7cfe68 to your computer and use it in GitHub Desktop.
Save sidharrth2002/5bd04e5bb0d8f6a3cbf42cbdeb7cfe68 to your computer and use it in GitHub Desktop.
import { createSlice } from "@reduxjs/toolkit";
import cookie from "js-cookie";
export const authSlice = createSlice({
name: "auth",
initialState: {
user:
cookie.get("user") !== undefined ? JSON.parse(cookie.get("user")) : {},
isAuthenticated: cookie.get("accessToken") ? true : false,
accessToken: cookie.get("accessToken") ? cookie.get("accessToken") : "",
},
// fix all this
reducers: {
LOGIN: (state, action) => {
state.user = action.payload.user;
state.accessToken = action.payload.accessToken;
state.isAuthenticated = true;
cookie.set("user", JSON.stringify(action.payload.user));
cookie.set("isAuthenticated", true);
cookie.set("accessToken", action.payload.accessToken);
},
LOGOUT: (state) => {
state.isAuthenticated = false;
state.accessToken = "";
state.user = null;
cookie.set("user", null);
cookie.set("isAuthenticated", false);
cookie.set("accessToken", "");
},
UPDATE: (state, action) => {
state.user = action.payload;
},
},
});
export const { LOGIN, LOGOUT, UPDATE_USER } = authSlice.actions;
export const selectIsAuthenticated = (state) => state.isAuthenticated;
export const selectUser = (state) => state.user;
export default authSlice.reducer;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment