3

I'm trying to remove all user data from the persisted state, when a user logs out. For managing my state I'm using Zustand and followed this guide: https://docs.pmnd.rs/zustand/guides/typescript

I'm creating my store as follows:

export const useStore = create<Slices>()(
  persist(
    devtools((...x) => ({
      ...createProfileSlice(...x),
      ...createSessionSlice(...x),
      ...createStatusSlice(...x),
    })),
    {
      name: CONFIGURATION.STATE.NAME,
      partialize: (state) => Object.fromEntries(Object.entries(state).filter(([key]) => !['session', 'isLoading'].includes(key))),
    }
  )
);

My question is now, how to remove all data from the persisted store, when a user logs out. I've tried to clear the localstorge with localstorage.clear(), but Zustand sets the whole state when the next change at the state is done again.

I've also found the following guide: https://docs.pmnd.rs/zustand/guides/how-to-reset-state This guide uses another structure and honestly I don't understand what is going on. How can I delete all user data from the persisted state when a user logs out?

Robin
  • 8,162
  • 7
  • 56
  • 101

2 Answers2

1

It is a piece of a cake. as the docs says about updating multiple stores in slicing patterns:

you create a slice to make changes in multiple slices :

import { createBearSlice } from './bearSlice'
import { createFishSlice } from './fishSlice'

export const resetAllSlices = (set) => ({
  resetAll: () => {
    createBearSlice(set).reset()
    createFishSlice(set).reset()
  },
})

then import this slice to your main store:

import { create } from 'zustand'
import { createBearSlice } from './bearSlice'
import { createFishSlice } from './fishSlice'
import { resetAllSlices } from './resetAllSlices'

export const useBoundStore = create((...a) => ({
  ...createBearSlice(...a),
  ...createFishSlice(...a),
  ...resetAllSlices(...a),
}))

and use it in a component like below:

export const myComponent = ()=>{
  const resetState = useStore((state) => state.resetAll);

  resetState();
}
1

I will leave it here in case someone else faces the same problem; I got the same problem. Here is how I solved it


export const useAuth = create(
  persist(
    (set) => ({
      user: {},
      setUser: (user) =>
        set(() => ({
          user: user,
        })),
      logout: () => {
        set(() => ({ user: null }));
        localStorage.removeItem("auth")<------- to remove data from localstorage
      }
    }),
    {
      name: "auth",
    }
  )
); ```


hope this help !