5.1.0 • Published 3 months ago

redux-remember v5.1.0

Weekly downloads
333
License
MIT
Repository
github
Last release
3 months ago

NPM Version Build Status Coverage Status NPM Downloads

Logo

Redux Remember saves and loads your redux state from a key-value store of your choice.

Important

The current version of Redux Remember is tested working with redux@5.0.0+ and redux-toolkit@2.0.1+. In case you want to use this library with an older versions of Redux or Redux Toolkit you might need to switch back to version 4.2.2 of Redux Remember.

Key features:

  • Saves (persists) and loads (rehydrates) only allowed keys and does not touch anything else.
  • Completely unit and battle tested.
  • Works on both web (any redux compatible app) and native (react-native).

Works with any of the following:

  • AsyncStorage (react-native)
  • LocalStorage (web)
  • SessionStorage (web)
  • Your own custom storage driver that implements setItem(key, value) and getItem(key)

See demo!

Installation

$ npm install --save redux-remember
# or
$ yarn add redux-remember

Usage - web

import { configureStore, createSlice, PayloadAction } from '@reduxjs/toolkit';
import { rememberReducer, rememberEnhancer } from 'redux-remember';

const myStateIsRemembered = createSlice({
  name: 'persisted-slice',
  initialState: {
    text: ''
  },
  reducers: {
    setPersistedText(state, action: PayloadAction<string>) {
      state.text = action.payload;
    }
  }
});

const myStateIsForgotten = createSlice({
  name: 'forgotten-slice',
  initialState: {
    text: ''
  },
  reducers: {
    setForgottenText(state, action: PayloadAction<string>) {
      state.text = action.payload;
    }
  }
});

const reducers = {
  myStateIsRemembered: myStateIsRemembered.reducer,
  myStateIsForgotten: myStateIsForgotten.reducer,
  someExtraData: (state = 'bla') => state
};

export const actions = {
  ...myStateIsRemembered.actions,
  ...myStateIsForgotten.actions
};

const rememberedKeys = [ 'myStateIsRemembered' ]; // 'myStateIsForgotten' will be forgotten, as it's not in this list

const reducer = rememberReducer(reducers);
const store = configureStore({
  reducer,
  enhancers: (getDefaultEnhancers) => getDefaultEnhancers().concat(
    rememberEnhancer(
      window.localStorage, // or window.sessionStorage, or your own custom storage driver
      rememberedKeys
    )
  )
});

// Continue using the redux store as usual...

Usage - react-native

import AsyncStorage from '@react-native-async-storage/async-storage';
import { configureStore, createSlice, PayloadAction } from '@reduxjs/toolkit';
import { rememberReducer, rememberEnhancer } from 'redux-remember';

const myStateIsRemembered = createSlice({
  name: 'persisted-slice',
  initialState: {
    text: ''
  },
  reducers: {
    setPersistedText(state, action: PayloadAction<string>) {
      state.text = action.payload;
    }
  }
});

const myStateIsForgotten = createSlice({
  name: 'forgotten-slice',
  initialState: {
    text: ''
  },
  reducers: {
    setForgottenText(state, action: PayloadAction<string>) {
      state.text = action.payload;
    }
  }
});

const reducers = {
  myStateIsRemembered: myStateIsRemembered.reducer,
  myStateIsForgotten: myStateIsForgotten.reducer,
  someExtraData: (state = 'bla') => state
};

export const actions = {
  ...myStateIsRemembered.actions,
  ...myStateIsForgotten.actions
};

const rememberedKeys = [ 'myStateIsRemembered' ]; // 'myStateIsForgotten' will be forgotten, as it's not in this list

const reducer = rememberReducer(reducers);
const store = configureStore({
  reducer,
  enhancers:  (getDefaultEnhancers) => getDefaultEnhancers().concat(
    rememberEnhancer(
      AsyncStorage, // or your own custom storage driver
      rememberedKeys
    )
  )
});

// Continue using the redux store as usual...

Usage - inside a reducer

import { createSlice, createAction, PayloadAction } from '@reduxjs/toolkit';
import { REMEMBER_REHYDRATED, REMEMBER_PERSISTED } from 'redux-remember';

type InitialState = {
  changeMe: any;
  rehydrated: boolean;
  persisted: boolean;
};

const initialState: InitialState = {
  changeMe: null,
  rehydrated: false,
  persisted: false
};

const myReducer = createSlice({
  name: 'my-reducer',
  initialState,
  reducers: {
    someAction(state, action: PayloadAction<{ changeMe: any }>) {
      if (!state.rehydrated) {
        return;
      }

      state.changeMe = action.payload.changeMe;
    }
  },
  extraReducers: (builder) => builder
    .addCase(createAction<{ myReducer?: InitialState }>(REMEMBER_REHYDRATED), (state, action) => {
      // @INFO: action.payload.myReducer => rehydrated state of this reducer or "undefined" during the first run
      state.changeMe = action.payload.myReducer?.changeMe || null;
      state.rehydrated = true;
    })
    .addCase(createAction<{ myReducer?: InitialState }>(REMEMBER_PERSISTED), (state, action) => {
      // @INFO: action.payload.myReducer => persisted state of this reducer or "undefined" in case this reducer is not persisted
      state.rehydrated = false;
      state.persisted = true;
    })
});

const reducers = {
  myReducer: myReducer.reducer,
  // ...
};

const reducer = rememberReducer(reducers);
const store = configureStore({
  reducer,
  enhancers: (getDefaultEnhancers) => getDefaultEnhancers().concat(
    rememberEnhancer(
      window.localStorage, // or window.sessionStorage, or AsyncStorage, or your own custom storage driver
      rememberedKeys
    )
  )
});

// Continue using the redux store as usual...

Usage - legacy apps (without redux toolkit)

Examples here are using redux toolkit. If your application still isn't migrated to redux toolkit, check the legacy usage documentation.

API reference

  • rememberReducer(reducers: Reducer | ReducersMapObject)
    • Arguments:
      1. reducers (required) - takes the result of combineReducers() function or list of non-combined reducers to combine internally (same as redux toolkit);
    • Returns - a new root reducer to use as first argument for the configureStore() (redux toolkit) or the createStore() (plain redux) function;
  • rememberEnhancer(driver: Driver, rememberedKeys: string[], options?: Options)
    • Arguments:
      1. driver (required) - storage driver instance, that implements the setItem(key, value) and getItem(key) functions;
      2. rememberedKeys (required) - an array of persistable keys - if an empty array is provided nothing will get persisted;
      3. options (optional) - plain object of extra options:
        • prefix: storage key prefix (default: '@@remember-');
        • serialize - a plain function that takes unserialized store state and its key (serialize(state, stateKey)) and returns serialized state to be persisted (default: JSON.stringify);
        • unserialize - a plain function that takes serialized persisted state and its key (serialize(state, stateKey)) and returns unserialized to be set in the store (default: JSON.parse);
        • persistThrottle - how much time should the persistence be throttled in milliseconds (default: 100)
        • persistDebounce (optional) - how much time should the persistence be debounced by in milliseconds. If provided, persistence will not be throttled, and the persistThrottle option will be ignored. The debounce is a simple trailing-edge-only debounce.
        • persistWholeStore - a boolean which specifies if the whole store should be persisted at once. Generally only use this if you're using your own storage driver which has gigabytes of storage limits. Don't use this when using window.localStorage, window.sessionStorage or AsyncStorage as their limits are quite small. When using this option, key won't be passed to serialize nor unserialize functions - (default: false);
        • errorHandler - an error handler hook function which is gets a first argument of type PersistError or RehydrateError - these include a full error stack trace pointing to the source of the error. If this option isn't specified the default behaviour is to log the error using console.warn() - (default: console.warn);
        • initActionType (optional) - a string which allows you to postpone the initialization of Redux Remember until an action with this type is dispatched to the store. This is used in special cases whenever you want to do something before state gets rehydrated and persisted automatically (e.g. preload your state from SSR). NOTE: With this option enabled Redux Remember will be completely disabled until dispatch({ type: YOUR_INIT_ACTION_TYPE_STRING }) is called;
    • Returns - an enhancer to be used with Redux
5.1.0

3 months ago

5.0.1

4 months ago

5.0.0

4 months ago

4.2.2

4 months ago

4.2.1

4 months ago

4.2.0

4 months ago

4.1.0

4 months ago

4.0.4

7 months ago

4.0.1

8 months ago

4.0.0

8 months ago

4.0.3

7 months ago

4.0.2

7 months ago

3.1.10

1 year ago

3.3.1

11 months ago

3.3.0

11 months ago

3.2.1

11 months ago

3.2.0

1 year ago

3.1.9

1 year ago

3.1.8

1 year ago

3.1.3

1 year ago

3.1.2

1 year ago

3.1.7

1 year ago

3.1.6

1 year ago

3.1.5

1 year ago

3.1.4

1 year ago

3.1.1

2 years ago

3.1.0

2 years ago

2.2.0

2 years ago

3.0.1

2 years ago

3.0.0

2 years ago

2.1.4

3 years ago

2.1.2

3 years ago

2.1.3

3 years ago

2.1.1

3 years ago

2.1.0

3 years ago

2.0.7

4 years ago

2.0.6

4 years ago

2.0.5

5 years ago

2.0.4

5 years ago

2.0.3

5 years ago

2.0.2

5 years ago

2.0.1

5 years ago

2.0.0

5 years ago

1.0.14

5 years ago

1.0.13

5 years ago

1.0.12

6 years ago

1.0.11

6 years ago

1.0.10

6 years ago

1.0.9

6 years ago

1.0.8

6 years ago

1.0.7

6 years ago

1.0.6

6 years ago

1.0.5

6 years ago

1.0.4

6 years ago

1.0.3

6 years ago

1.0.2

6 years ago

1.0.1

6 years ago

1.0.0

6 years ago