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;