Home > other >  How to add item in redux with dictionary type in react typescript
How to add item in redux with dictionary type in react typescript

Time:02-13

I am using react-redux with typescript. I am importing a JSON file in my redux slice for an initial value. Now, I want to perform a crud operation on a dictionary. I want to add item only in the required key, for that what will be the type structure and how do I perform the operation?

my external JSON contains employee data with respect to the department. department as a key and employees as an array of objects. my structure looks like below:

{
  "0": [{...},{...},{...}],
  "1": [{...},{...},{...}],
  "2": [{...},{...},{...}],
}

My slice code looks like this:

type employeeType = {
    id: number,
    name: string,
    age: number,
    DOB: number
}

type departments = {
    [departmentNo: string]: employeeType[];
}

const initialState:departments = require("./data.json");


export const employeeReducer = (state: departments = initialState, action: any) => {
    switch (action.type){
        case "ADD_EMPLOYEE": {
            return ({})
        }
        default: {
            return state
        }
    }
}

CodePudding user response:

Think about what information you need in order to make the correct modification to state. Your state is keyed by department number, so in order to add a new employee you will need to know which department you are adding them to. You also need to know all the details of the employee object. Your action.payload might look like this:

interface AddEmployeePayload {
    departmentNo: string;
    employee: EmployeeType;
}

I highly recommend creating your reducer with Redux Toolkit so that you can use a simple push operation instead of dealing with immutable nested updates.

It's up to you how you want to handle cases where the departmentNo doesn't match an existing array on your state object. Throw an error? Create a new array?

import { createSlice, PayloadAction } from '@reduxjs/toolkit';

const employeeSlice = createSlice({
  name: 'employees',
  initialState,
  reducers: {
    addEmployee: (state, action: PayloadAction<AddEmployeePayload>) => {
      // Get the data from our action.
      const { departmentNo, employee } = action.payload;
      // Access the existing array of employees in this department.
      const employeeArray = state[departmentNo];
      if (employeeArray) {
        // Add this employee to the array.
        employeeArray.push(employee);
      } else {
        // Warn about potential invalid ids.
        console.warn(`Unknown department number ${departmentNo}.`);
        // Create a new department array with just this employee in it.
        state[departmentNo] = [employee];
      }
    }
  }
})


export const employeeReducer = employeeSlice.reducer;

// action creator function
export const { addEmployee } = employeeSlice.actions;

Complete Code

  • Related