Home > Enterprise >  How can I assign the filtered data to the state of the Reducer?
How can I assign the filtered data to the state of the Reducer?

Time:08-07

I'm applying Typescript and Reducers in a simple project but I can't make it so that when I delete a data from the array of objects I can update the state. The error:

Type '{ newData: Contactos[]; contacts: Contactos[]; }' is not assignable to type 'ContactsState'. Object literal may only specify known properties, and 'newData' does not exist in type 'ContactsState'.

It is taking newData as a property

import React from 'react';

interface Contactos {
  id: number;
  name: string;
  email: string;
  phone: string;
}

interface ContactsState {
  contacts: Contactos[];
}

type ContactsReducerAction = {
  type: 'delete';
  payload: {
    id: number;
  };
};

const INITIAL_STATE = [
  {
    id: 1,
    name: 'John Doe',
    email: '[email protected]',
    phone: '555-555-5555',
  },
  {
    id: 2,
    name: 'Karen Williams',
    email: '[email protected]',
    phone: '222-222-2222',
  },
  {
    id: 3,
    name: 'Henry Johnson',
    email: '[email protected]',
    phone: '111-111-1111',
  },
];

export const contactsReducer = (
  state: ContactsState,
  action: ContactsReducerAction
): ContactsState => {
  switch (action.type) {
    case 'delete': {
      let newData = state.contacts.filter(el => el.id !== action.payload.id);

      return {
        ...state,
        newData,
      };
    }

    default:
      return state;
  }
};

CodePudding user response:

I'm assuming you want to overwrite the contacts list with the filtered data. You are returning a new property called newData which TypeScript wont allow because it's not a property defined in ContactsState. I think you meant this:

export const contactsReducer = (
  state: ContactsState,
  action: ContactsReducerAction
): ContactsState => {
  switch (action.type) {
    case 'delete': {
      let contacts = state.contacts.filter(el => el.id !== action.payload.id);

      return {
        ...state,
        contacts,
      };
    }

    default:
      return state;
  }
};

  • Related