7
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

redux-persit を使わずに Redux と localStorage を同期

Last updated at Posted at 2019-03-14

redux-persist を使うと Redux のstate をlocalStorage に自動的に反映してくれるので便利。
しかし state のネストの深いところの数箇所くらいしか永続化しない場合、 redux-persist では難しい。(できなくはないが書き方がまわりくどくなる印象)
なのでredux-persist を使う代わりに、自前で Middleware を書いて実装してみた。

Middleware で action発火前と発火後のstate を見て、 auth.user.jwt state に変化があったら localStorageを操作する。

// store.js

// ...

const localStorageMiddleware: Middleware<
  {},
  State
> = store => next => action => {
  const prevJwt = store.getState().auth.user.jwt
  next(action)
  const nextJwt = store.getState().auth.user.jwt
  if (prevJwt === nextJwt) return
  if (nextJwt) {
    localStorage.setItem('jwt', nextJwt)
    return
  }
  localStorage.removeItem('jwt')
}

const store = createStore(
  reducer,
  composeEnhancers(applyMiddleware(thunk, localStorageMiddleware)),
)

// ...

該当 state の初期値に localStorage.getItem() の値を入れる。

// auth/reducer.js

// ...

const initialState: State = {
  isLogin: false,
  user: {
    jwt: localStorage.getItem('jwt') || '',
  },
  // ...
}

// ...

これで指定したstate が localStorage に自動的に反映され、同期するようになる。

7
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?