-
Create a feature file describing the slice name.
touch feature/assignmentSlice.js
-
Define an initial state.
const initialState = { showActions: false, assignmentId: null }
-
Define the name, initialState and reducers from the slice.
import { createSlice } from '@reduxjs/toolkit' const assignmentSlice = createSlice({ name: 'assignmentTable', initialState, reducers: { show: (state, action) => { state.showActions = true state.assignmentId = context.payload }, hide: (state) => { state.showActions = false } } })
-
Export the slice actions.
export const { hide, show } = assignmentSlice.actions
-
Export the slice reducer.
export default assignmentSlice.reducer
-
Add the reducer to the
store.reducer
definition.import assignmentSliceReducer from './feature/assignmentSlice' const store = configureStore({ reducer: { assignment: assignmentSliceReducer } })
- Read the state.
import { useSelector } from 'react-redux' const MyComponent = () => { const showActions = useSelector((state) => state.assignment.showActions) return <p> The showActions value is {showActions}</p> } export default MyComponent
- Call actions.
import { useDispatch } from 'react-redux' import { show, hide } from './feature/assignmentSlice' const MyComponent = () => { const dispatch = useDispatch() return ( <> <button onClick={() => dispatch(show(1))}>Show with payload</button> <button onClick={() => dispatch(hide())}>Hide</button> </> ) } export default MyComponent
- Ensure to create a type or interface for the initial state of your slice.
interface InitialState {
showActions: boolean,
assignmentId: number|null
}
- Define the payload typein your createSlice.reducer definition:
import { createSlice, PayloadAction } from '@reduxjs/toolkit'
const assignmentSlice = createSlice({
/*...*/
reducers: {
show: (state, action: PayloadAction<number>) => {
state.showActions = true
state.assignmentId = context.payload
}
}
})
- When you export your store, ensure to define the root state type, it can be easily done by inferring it
const store = configureStore({/*...*/})
export type RootState = ReturnType<typeof store.getState>
export type AppDispatch = typeof store.dispatch
- Use the root types to have autocompletion
import React from 'react'
import { useSelector } from 'react-redux'
import { RootState } from '../store'
const MyComponent = () => {
const showActions = useSelector((state: RootState) => state.tableAction.showActions)
/*...*/
}
export default MyComponent
- Clone the repository.
- Move to the directory.
- Install the dependencies.
npm i
- Run the start script.
npm run start