Last active
November 25, 2022 17:49
-
-
Save JonasDoe/47a93c72945c49d790400ea9a0aeaf9e to your computer and use it in GitHub Desktop.
React-Redux with TypeScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { configureStore, createSlice, PayloadAction } from '@reduxjs/toolkit'; | |
import { useSelector, useDispatch } from 'react-redux'; | |
export const mySlice = createSlice({ | |
name: 'MyItem', | |
initialState: { field1: 'hello, world', field2: 0 }, | |
reducers: { | |
setField: (state: { field1: string; field2: number }, action: PayloadAction<string>) => { | |
state.field1 = action.payload; | |
}, | |
}, | |
}); | |
export const store = configureStore({ | |
reducer: { | |
myItem: mySlice.reducer, | |
}, | |
}); | |
export type AppDispatch = typeof store.dispatch; | |
export const useAppDispatch: () => AppDispatch = useDispatch; | |
// For some reason we need to use this pattern since `dispatch(mySlice.actions.setField)` doesn't work. | |
const {setField} = mySlice.actions | |
useAppDispatch(setField('newValue')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment