skip to Main Content

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

I create 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 try 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.

2

Answers


  1. 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 which case you will need to change this part of the reducer:

    gridPolygonsData[currentArea] = {
      ...gridPolygonsData[currentArea],
      waypointToEdit: action.payload,  // change
    };
    
    Login or Signup to reply.
  2. You define the interface as the following.

    export interface WaypointToEditPayload {
     waypoint: Waypoint | RequiredWaypoint | null;
    }
    

    So the reducer can accept {waypoint: Waypoint | RequiredWaypoint | null}, but your getWaypoint function possibly return just null instead of {waypoint: null}.

    You just fix the function returning {waypoint: null} when it needs to return null.

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