0
0

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 3 years have passed since last update.

React Redux の Storeを空にする

Last updated at Posted at 2021-02-20

React, Redux, ReduxToolKitにかまけていたら、storeキャッシュの方法がsliceの範囲外だったため、それの備忘録

TL;DR

root reducerを設置して、storeにundefinedを設定する、

action.ts
import { createAction } from "@reduxjs/toolkit";

export const clearCacheBase = createAction('[CORE/STIORE] Clear Store Cache')

export const clearCache = () => {
    return clearCacheBase()
}
reducer.tsx
import { combineReducers, configureStore } from "@reduxjs/toolkit"
import * as fromTodo from "./todo"
import { clearCacheBase } from "./core/action"

const combinedReducer = combineReducers({
    [fromTodo.featureName]: fromTodo.reducer
})

export const reducers = (state, action) => {
    if(action.type === clearCacheBase.toString()) {
        state = undefined // undefinedを追加するとstoreが初期値に全て戻る
        // return combinedReducer(undefined, action)でも動く こっちの方が再代入なく直感的かも
    }
    return combinedReducer(state, action)
}

export type RootReducer = typeof reducers
component.tsx
import React from 'react';
import { useDispatch } from "react-redux"
import { clearCache } from "../store/core/action"

/* eslint-disable-next-line */
export interface ButtonProps {}

export function Button(props: ButtonProps) {
  const dispatch = useDispatch()
  return (
    <div>
      <button onClick={() => dispatch(clearCache())}>clear cache</button>
    </div>
  );
}

export default Button;

レポ diff

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?