Question:
Why Redux-toolkit payload don't reconigze type in TypeScript?

Problem

I am using redux-toolkit in my project and I got this problem


I created this reducer:


setWaypointToEdit: (state, action: PayloadAction<WaypointToEditPayload>) => {


  let gridPolygonsData: GridPolygonsData;

  const { currentArea } = state.areas;      

  

  gridPolygonsData = {

    ...state.areas.gridPolygonsData,

  };


  gridPolygonsData[currentArea] = {

    ...gridPolygonsData[currentArea],

    waypointToEdit: action.payload.waypoint,

  };

  

 state = {

    ...state,

    areas: {

      ...state.areas,

      gridPolygonsData,

    },

 }


}, 


With this payload:


export interface WaypointToEditPayload {


 waypoint: Waypoint | RequiredWaypoint | null;


}


But I got an error when I tried to dispatch this method:


setWaypointToEdit(this.getWaypoint(areaNumber, waypointId))



enter image description here

This is what the above method do

private getWaypoint(areaNumber: number, waypointId: number) {

const {


    areas: { gridPolygonsData }


} = useAppSelector((state) => state.project); 

const waypoints = gridPolygonsData[areaNumber].gridWaypoints;

if (waypoints)

  return waypoints.find((waypoint) => waypoint.id === waypointId) ?? null;

return null;


}


Even returning two types: Waypoint or null, a still got this error. does anyone could help me? Thank's.


Solution

Your reducer expects an object. Either send the waypoint in an object with property waypoint:

setWaypointToEdit({ waypoint: this.getWaypoint(areaNumber, waypointId) })


Or change the expected type:

export type WaypointToEditPayload = Waypoint | RequiredWaypoint | null;


In this case, you will need to change this part of the reducer:

gridPolygonsData[currentArea] = {

  ...gridPolygonsData[currentArea],

  waypointToEdit: action.payload// change

};


Suggested blogs:

>Why Typescript does not allow a union type in an array?

>Narrow SomeType vs SomeType[]

>Create a function that convert a dynamic Json to a formula in Typescript

>How to destroy a custom object within the use Effect hook in TypeScript?

>How to type the values of an object into a spreadsheet in TypeScript?

>Type key of record in a self-referential manner in TypeScript?

>How to get the last cell with data for a given column in TypeScript?

>Ignore requests by interceptors based on request content in TypeScript?

>Create data with Typescript Sequelize model without passing in an id?

>How to delete duplicate names from Array in Typescript?


Nisha Patel

Nisha Patel

Submit
0 Answers