Skip to content

Instantly share code, notes, and snippets.

@akursat
Created September 20, 2021 07:51
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 akursat/d9a4dcb71a71dbf03f94b62be7bb99c2 to your computer and use it in GitHub Desktop.
Save akursat/d9a4dcb71a71dbf03f94b62be7bb99c2 to your computer and use it in GitHub Desktop.
redux toolkit authslice
const slice = createSlice({
name: 'auth',
initialState: { user: null, token: null, isAuthenticated: false } as AuthState,
reducers: {
logout: (state) => {
state.user = null
state.token = null
state.isAuthenticated = false
},
},
extraReducers: (builder) => {
builder.addMatcher(
api.endpoints.login.matchFulfilled,
(state, { payload: { user, token } }) => {
state.user = user
state.token = token
state.isAuthenticated = true
},
)
},
})
export const { logout } = slice.actions
export default slice.reducer
export const selectCurrentUser = (state: RootState) => state.auth.user
export const selectIsAuthenticated = (state: RootState) => state.auth.isAuthenticated
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment