Created
December 19, 2021 15:33
-
-
Save sidharrth2002/5bd04e5bb0d8f6a3cbf42cbdeb7cfe68 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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