Skip to main content

Posts

Showing posts with the label redux toolkit

Mimicking React State in Redux Toolkit with Objects and Hooks

To mimic React state in Redux Toolkit, you can use the createSlice function with the initialState and reducers options. The initialState option defines the initial state of your slice, and the reducers option defines how the state should be updated in response to actions. Here's an example of how to mimic a React state object that manages a list of items: import { createSlice } from "@reduxjs/toolkit"; const initialState = { items: {}, }; const itemsSlice = createSlice({ name: "items", initialState, reducers: { addItem: (state, action) => { state.items[action.payload.id] = action.payload; }, updateItem: (state, action) => { state.items[action.payload.id] = action.payload; }, removeItem: (state, action) => { delete state.items[action.payload.id]; }, }, }); export const { addItem, updateItem, removeItem } = itemsSlice.actions; export default itemsSlice.reducer; This slice defines an initial state wit...

Topics

Show more