elgerlambert / redux-localstorage

Store enhancer that syncs (a subset) of your Redux store state to localstorage.
MIT License
1.32k stars 107 forks source link

How to know when state is rehydrated? #82

Open JimLynchCodes opened 6 years ago

JimLynchCodes commented 6 years ago

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.

gregorskii commented 6 years ago

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 🤷‍♂️