The type 'IContact[]' given does not match the expected type 'FetchContactsSuccessPayload' for the parameter

I've been diving into my project involving react redux-saga with TypeScript and I'm facing an issue with a type error within my saga file. This is my first experience with TypeScript.

The error originates from the saga.ts file, specifically this code snippet:

yield put(fetchContactsSuccess(data)).

The error message reads as follows:

Argument of type 'IContact[]' is not assignable to parameter of type 'FetchContactsSuccessPayload'.

Property 'contacts' is missing in type 'IContact[]' but required in type 'FetchContactsSuccessPayload'.

I am uncertain about what I might be overlooking or misunderstanding.

In my types.ts file:

export interface FetchContactsSuccessPayload {
    contacts: IContact[]
}

export type FetchContactsRequest = {
    type: typeof GET_ALL_CONTACTS_REQUEST
}

export type FetchContactsSuccess = {
    type: typeof GET_ALL_CONTACTS_SUCCESS,
    payload: FetchContactsSuccessPayload
}

export type FetchContactsError = {
    type: typeof GET_ALL_CONTACTS_ERROR,
    payload: {message: string}
}

Within actions.ts:

export const fetchContactsRequest = (): FetchContactsRequest => ({
    type: GET_ALL_CONTACTS_REQUEST,
})

export const fetchContactsSuccess = (payload: FetchContactsSuccessPayload): FetchContactsSuccess => ({
    type: GET_ALL_CONTACTS_SUCCESS,
    payload
})

export const fetchContactsError = (error: any) => ({
    type: GET_ALL_CONTACTS_ERROR,
    error
})

Regarding reducers.ts:

export const contactReducer = (state=initialState, action: ProjectActionTypes) => {
    switch (action.type) {
        case GET_ALL_CONTACTS_REQUEST:
            return {
                ...state,
                pending: true,
            };
        case GET_ALL_CONTACTS_SUCCESS:
            return {
                ...state,
                pending: false,
                contacts: action.payload
            }
        case GET_ALL_CONTACTS_ERROR:
            return {
                ...state,
                pending: false,
                error: action.payload
            };
        default:
            return state;
    }
}

And finally, in saga.ts:

export function* fetchContacts() {
    try {
        const data: IContact[]  = yield call(getContacts)
        console.log(data);
        
       yield put(fetchContactsSuccess(data))
    } catch (error) {
        
    }
}

export function* fetchAllContactsSaga() {
    yield takeEvery(GET_ALL_CONTACTS_REQUEST, fetchContacts)
}


export default function* rootSaga() {
    yield all([fork(fetchAllContactsSaga)])
}

Even after attempting to use type 'any' instead of IContact[], the issue persists. When I log the response, I receive a status code of 200 indicating that it's functioning properly, yet GET_ALL_CONTACTS_REQUEST never seems to trigger.

Answer №1

export interface ReceivedContactsPayload {
    contactList: IContact[]
}

The ReceivedContactsPayload object contains a property called contactList, which holds an array of contacts. This payload should be passed as an argument to the receiveContacts action creator. However, you are currently invoking receiveContacts(data) with just the array of contacts.

Solution 1: Adjust your saga functionality

Instead of passing just an array, provide a payload object.

const data: IContact[] = yield call(getContacts)
yield put(receiveContacts({ contactList: data }))

Solution 2: Update your action creator method

Modify the action creator to accept an array directly instead of a payload object.

export const receiveContacts = (contacts: IContact[]): ReceivedContactsAction => ({
    type: RECEIVE_ALL_CONTACTS,
    payload: { contactList }
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Intellisense fails to function properly after attempting to import a custom npm package

I've encountered an issue with a custom npm package that I created using storybook. The components function properly in other projects when imported, but the intellisense feature is not working as expected. Interestingly, when I import the same compon ...

Encountering an issue post-upgrade with Angular 7 project

Currently, I am facing an issue with upgrading a project from Angular 6 to version 7. Despite following multiple online tutorials and successfully completing the upgrade process, I encountered an error when running the 'ng serve' command: ERROR ...

Enhance React component props for a styled component element using TypeScript

Looking to enhance the properties of a React component in TypeScript to include standard HTML button attributes along with specific React features such as ref. My research suggests that React.HTMLProps is the ideal type for this purpose (since React.HTMLA ...

The issue encountered is a TypeError stating that it is unable to retrieve properties of an undefined value, specifically in relation to the 'imageUrl

When I include the following line of HTML code: <td> <img align="center" [src]="productByBarCode.imageUrl" /> </td> An error is thrown by the console: ERROR TypeError: Cannot read properties of undefined (reading &a ...

Encountering an issue while running the ng build --prod command in Angular

I ran into an issue while trying to execute the command ng build --prod in Angular. I've completed my small project and now need to generate the necessary files for uploading to my hosting provider. ERROR - ANGULAR CLI C:\Users\Johan Cor ...

There is no index signature that includes a parameter of type 'number' on the specified type xx

Here are the data types I am currently utilizing: export interface IHelpDeskTextData { supportPaneltext: ContactHelpdeskContex[]; selected?: number | null; brandOptions?: string[]; textPanel?: ITextPanel[]; } export class ContactHelpdeskContex { ...

Bring in d3 along with d3-force-attract

Recently, I have installed D3 along with d3-force-attract. npm install @types/d3 -S npm install -S d3-force-attract I am currently facing an issue with importing d3 force attract as it is not recognized as a typescript module, unlike d3 itself. The inco ...

Apply criteria to an array based on multiple attribute conditions

Given an array containing parent-child relationships and their corresponding expenses, the task is to filter the list based on parents that have a mix of positive and negative expenses across their children. Parents with only positive or negative child exp ...

Steps for assigning the TAB key functionality within a text area

Is there a way to capture the TAB key press within a text area, allowing for indentation of text when the user uses it? ...

Using selectors and mappers in Typescript generics

I am looking to create a versatile selector and mapper method. interface State { user: { name: string; age: number; } } const pickName = (state: State) => state.user.name; const selectAge = (state: State) => state.user.age; ...

Modifying the value of a React input component is restricted when the "value" field is utilized

I'm currently utilizing material-UI in my React application. I am facing a challenge where I need to remove the value in an input field by clicking on another component. The issue arises when using the OutlinedInput component with a specified value. ...

`When is it appropriate to utilize dispatch within an action creator function?`

I have created two functions in my ActionCreator.js file. First: export const fetchAudioForVerification = ()=>{ return fetch(baseUrl+'audio',{ // Perform Get Request } .then(response=>response.json());} Second: export const handleAudio ...

The Power of Angular 2's Reactive Form Validation

I am currently developing a custom validator for a group of inputs within my dynamic form. this.transitionForm = this.fb.group({ effectiveStartDate: [this.utils.dateToISO(startDate), Validators.compose([Validators.required, this.validateDates])], effe ...

Experiencing compatibility issues with NextAuth and Prisma on Netlify when using NextJS 14

While the website is functioning correctly on development and production modes, I am encountering issues when testing it on my local machine. After deploying to Netlify, the website fails to work as expected. [There are errors being displayed in the conso ...

Is there a method to prevent explicitly passing the context of "this"?

Currently, I am in the process of developing a new product and have set up both back-end and front-end projects. For the front-end, I opted to use Angular framework with Typescript. As a newcomer to this language (just a few days old), I have encountered a ...

Typescript: When using ts-node-dev, an error occurred while trying to import express due to an unexpected

I am embarking on a fresh project using Typescript and I intend to set up the node server with typescript utilizing express. There's a helpful tutorial that explains how to execute a Typescript file without going through the hassle of compiling files, ...

Include a conditional statement in ng keypress

When a user types a specific value into a text input, I want to display a specific div. This is what my template looks like: <input type="text" id="jobTitle" (click)="autoCompleteClick()" (keypress)="autoCompleteKeypress()" name="autocomplete" place ...

Combining URL parameters into an object with NestJS's HTTP module

Is there a method for passing URL parameters to the httpService in nestjs? I want to improve the readability of this URL without resorting to Axios as nest has its own HTTPModule. Currently, this is how it looks and functions: const response = await this. ...

Utilizing Typescript within Visual Studio Code alongside node_modules

I currently have typescript installed and am utilizing the powerful visual code editor. Whenever I attempt to navigate to the definition of a typescript function in the node_modules directory, Visual Studio Code ends up expanding the entire 'node_mod ...

Using @carbon/react in conjunction with Next.js version 13 leads to unconventional styling

Here's what I did to set up my Next.js application: npx create-next-app@latest I then installed the necessary package using: npm i -S @carbon/react The global styles in app/globals.scss were customized with this code snippet: @use '@carbon/reac ...