authSlice for user and token persisting

 avatar
unknown
javascript
a year ago
1.4 kB
7
Indexable
import { createSlice } from "@reduxjs/toolkit"
import { jwtDecode } from "jwt-decode"

// Gets token from localStorage and returns it decoded
const getInitialState = () => {
  const token = localStorage.getItem("token")
  if (token) {
    try {
      const decoded = jwtDecode(token)
      return {
        token,
        userId: decoded.id,
        username: decoded.username,
        name: decoded.name,
      }
    } catch (error) {
      console.error("Invalid token", error)
      localStorage.removeItem("token")
    }
  }
  return {
    token: null,
    userId: null,
    username: null,
    name: null,
  }
}

// Sets initial from already available token
// Or sets state to the provided token with setCredentials
const authSlice = createSlice({
  name: "auth",
  initialState: getInitialState(),
  reducers: {
    setCredentials: (state, action) => {
      const token = action.payload
      if (token) {
        const decoded = jwtDecode(token)
        state.token = token
        state.userId = decoded.id
        state.username = decoded.username
        state.name = decoded.name
        localStorage.setItem("token", token)
      }
    },
    logout: (state) => {
      state.userId = null
      state.username = null
      state.name = null
      state.token = null
      localStorage.removeItem("token")
    },
  },  
})

export const { setCredentials, logout } = authSlice.actions
export default authSlice.reducer
Editor is loading...
Leave a Comment