Skip to content

Instantly share code, notes, and snippets.

@JonasDoe
Last active November 25, 2022 17:49
Show Gist options
  • Save JonasDoe/47a93c72945c49d790400ea9a0aeaf9e to your computer and use it in GitHub Desktop.
Save JonasDoe/47a93c72945c49d790400ea9a0aeaf9e to your computer and use it in GitHub Desktop.
React-Redux with TypeScript
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