Skip to content

alexandersandberg/zustand-persist

 
 

Repository files navigation

Zustand persist

Persist and rehydrate state works on react and react native

Zustand is a small, fast and scaleable bearbones state-management solution.

This library is inspiring by https://github.com/rt2zz/redux-persist

Contributions are Welcome

Build Status npm version npm downloads

$ npm install zustand-persist
$ yarn add zustand-persist

Try Demo Here

Middleware

// if in react native
// import AsyncStorage from '@react-native-community/async-storage'

const { persist, purge } = configurePersist({
  storage: localStorage, // use `AsyncStorage` in react native
  rootKey: 'root', // optional, default value is `root`
})

const useStore = createStore(
  persist({
    key: 'auth', // required, child key of storage
    allowlist: ['isAuthenticated', 'user'], // optional, will save everything if allowlist is undefined
    denylist: [], // optional, if allowlist set, denylist will be ignored
  }, (set) => ({
    isAuthenticating: false,
    isAuthenticated: false,
    user: undefined,
    login: async (username, password) =>{
      set((state) => ({ isAuthenticating: true }))
      const { user } = await webLogin(username, password)
      set((state) => ({
        isAuthenticated: true,
        isAuthenticating: false,
        user,
      })),
    }
  }))
)

PersistGate

function App() {
  return (
    <PersistGate
      onBeforeLift={() => {
        console.log('onBeforeLift')
      }}
      loading={<Loading />}>
      <AppContent />
    </PersistGate>
  )
}

Todo

  • enhanced removing root logic

About

Persist and rehydrate state

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • JavaScript 75.3%
  • TypeScript 21.4%
  • HTML 2.0%
  • CSS 1.3%