redux-toolkit-optimistic

1.0.1 • Public • Published

Redux Toolkit Optimistic

https://www.npmjs.com/package/redux-toolkit-optimistic

Simple helper library for use with Redux Toolkit. MUST be used in conjunction with createEntityAdapter as well as createSlice OR createReducer.

  • Allows for updateOne or updateMany optimistic updates.
  • Works especially well the pending and rejected states of createAsyncThunk.

Installation

npm install -S redux-toolkit-optimistic

yarn add redux-toolkit-optimistic

Usage

Example Redux code:

import {
  createAsyncThunk,
  createEntityAdapter,
  createSlice,
} from '@reduxjs/toolkit';
import {
  performOptimisticUpdate,
  revertOptimisticUpdate,
} from 'redux-toolkit-optimistic';
 
export const myFunction = createAsyncThunk(
  'mySlice/myFunction',
  async ({ id, changes }) => {
    await persistChangesToDb(id, changes);
  },
);
 
const myAdapter = createEntityAdapter();
const mySlice = createSlice({
  name: 'mySlice',
  initialState: myAdapter.getInitialState(),
  reducers: {},
  extraReducers: {
    [myFunction.pending]: (state, action) =>
      performOptimisticUpdate(state, myAdapter, action.meta.arg),
    [myFunction.rejected]: (state, action) =>
      revertOptimisticUpdate(state, myAdapter, action.meta.arg.id),
  },
});
 
const reducer = spreadsSlice.reducer;
export default reducer;

And usage in React:

import { myFunction } from '../path/to/state';
 
dispatch(
  myFunction({
    id: 'someId',
    changes: { someKey: 'new value' },
  }),
);

License

MIT

Package Sidebar

Install

npm i redux-toolkit-optimistic

Weekly Downloads

60

Version

1.0.1

License

MIT

Unpacked Size

38.7 kB

Total Files

8

Last publish

Collaborators

  • phobos101