elgerlambert/redux-localstorage

How to know when state is rehydrated?

Opened this issue · 1 comments

Hi, I've looked at other similar saving-redux-state-to-local-storage libraries, an they sometimes offer a callback function that is called when the redux state has finished being rehydrated from local storage, but it seems like there is no callback function with this library. Can I safely assume that in my components which implement the mapStateToProps method I can access the locally stored state with this.props.x in my componentWillMount function?

Thanks, Jim.

As far as I am aware this library does not have a HOC that lets the components know the LS is loaded. What you can do is use the action types:

import { actionTypes } from 'redux-localstorage';

To set your own field to indicate this:

export default (state = INITIAL_STATE, action) => {
  switch (action.type) {
    case actionTypes.INIT:
      if (action.payload && action.payload.user) {
        const user = action.payload.user;
        // take only what is desired from LS
        return { ...state, ...{
          name: user.name,
          email: user.email,
          localStorageLoaded: true
        }};
      }
      return { ...state };

This way you know in a component localStorageLoaded is set.

This is using the v1 breaking changes build.

However... this does require that you do not persist this field to local storage, otherwise, the loaded prop will exist in the local storage upon hydration. Which technically is fine... as it is hydrated 🤷‍♂️