skip to Main Content
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.

enter image description here

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


  1. 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.

    import { createSlice } from '@reduxjs/toolkit';
    
    const initialState = {
      // Your initial state here
    };
    
    const slice = createSlice({
      name: 'mySlice',
      initialState,
      reducers: {
        // Your reducers here
      },
    });
    
    export const { reducer: mySliceReducer } = slice;
    export const { action1, action2 } = slice.actions;
    

    Redux Store Configuration:
    In your Redux store configuration, import and use the slice reducer directly.

    import { configureStore } from '@reduxjs/toolkit';
    import { mySliceReducer } from './path/to/mySlice';
    
    const store = configureStore({
      reducer: {
        mySlice: mySliceReducer,
        // other reducers...
      },
    });
    
    export default store;
    

    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.

    import React from 'react';
    import { useSelector } from 'react-redux';
    
    const MyComponent = () => {
      const data = useSelector((state) => state.mySlice.data);
      // Render your component based on the data
    };
    
    export default MyComponent;
    

    By following this pattern, you can keep the initialState private within your slice implementation and only expose the necessary parts to your UI.

    Login or Signup to reply.
  2. 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:

    const initialState: TodolistState = [{
      id: Date.now(),
      title: 'test title',
      body: 'test body',
      done: false
    }];
    

    Simply provide an empty array:

    const initialState: TodolistState = [];
    

    Array.prototype.map can handle empty arrays without issue.

    In other words, data.map(.....) of the empty array initialState value will simply be an empty array and valid JSX.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search