import { PayloadAction, createSlice } from "@reduxjs/toolkit"
type TodolistState = {
id: number,
title: string,
body: string,
done: boolean
}[]
const initialState: TodolistState = [{
id: Date.now(),
title: 'test title',
body: 'test body',
done: false
}]
const todoSlice = createSlice({
name: 'Todo',
initialState,
reducers: {
add: (state, action: PayloadAction<{ id: number, title: string, body: string, done: boolean }>) => {
state.push(action.payload)
},
remove: (state, action: PayloadAction<{ id: number, done: boolean }>) => {
state.splice(action.payload.id, 1)
}
}
})
This is my how I display my UI.
function Display() {
const data = useSelector((state:RootState) => state.todo)
const dispatch = useDispatch()
return (
<>
<Box sx={{ p: 2 }}>
{data.map((val, index) => (
<Paper
elevation={3}
sx={{
p: 2,
display: "flex",
flexDirection: 'column',
gap: "10px",
margin: "10px"
}}
key={index}
>
<div className="title">
<Typography variant="h5">{val.title}</Typography>
</div>
<div className="body">
<Typography variant="body1">{val.body}</Typography>
</div>
<div className="sf">
<form action="" className="formbtn">
<Button
variant="contained"
color="primary"
onClick={() => {
dispatch(remove({ id: index, done: true }))
}}
>
Done
</Button>
</form>
</div>
</Paper>
))}
</Box>
</>
)
}
export default Display
When I do show it like this initialState
will show in my UI. How can I remove it?
2
Answers
In Redux Toolkit, initialState is typically used when creating a slice using the createSlice function. If you don’t want to expose the initialState in your UI, you can achieve this by not directly referencing it in your components.
Slice Creation:
When creating a slice, avoid exporting the initialState. Instead, export only the slice reducer and any action creators.
Redux Store Configuration:
In your Redux store configuration, import and use the slice reducer directly.
Connecting to Components:
When connecting your components to Redux, use useSelector to access the state managed by your slice, but don’t directly reference initialState.
By following this pattern, you can keep the initialState private within your slice implementation and only expose the necessary parts to your UI.
If you don’t want the initial state to be rendered to the UI then simply don’t provide it.
Instead of the "test" initial state:
Simply provide an empty array:
Array.prototype.map
can handle empty arrays without issue.In other words,
data.map(.....)
of the empty arrayinitialState
value will simply be an empty array and valid JSX.