"Utilize the createReducer function with builder syntax to handle callbacks

Having trouble using createReducer with the builder syntax to update the auth state based on user login success or failure. Running into TS2769 error specifically in the second builder.addCase where adjusting the state for failed logins. Seeking assistance to identify and resolve the error within my code.

Here's a snippet of my code:

export interface AuthInterface {
    loading: boolean;
    userToken: boolean | null;
    error: string | null;
    success: boolean;
}

export interface AuthState {
    auth: AuthInterface;
}

const initialState: AuthState = {
    auth: {
        loading: false,
        userToken: null,
        error: null,
        success: false,
    }
}

// REST OF THE CODE SNIPPET HERE

Error encountered:

TS2769: No overload matches this call...

If replacing

action: PayloadAction<AuthInterface>
with action: any resolves the issue, but causing troubles with action.payload.error.

Answer №1

I managed to find a solution using the code snippet below:

export const authSlice = createSlice({
    name: "auth",
    initialState,
    reducers: {},
    extraReducers: (builder) => {
        builder
        .addCase(login.fulfilled, (state, action: PayloadAction<AuthInterface>) => {
            console.log(action);
            state.auth.loading = false;
            state.auth.success = true;
            state.auth.error = action.payload.error;
        })
        .addCase(login.rejected, (state, action: PayloadAction<any>) => {
            console.log(action);
            state.auth.success = false;
            state.auth.error = action.payload
        })
        
    }
});

I'm still puzzled as to why I can't use

action: PayloadAction<AuthInterface>

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

The Object filter is experiencing a delay with processing 10,000 items

When an API returns over 10,000 objects in the format of {firstName:'john',lastName:'Cena'}, I am faced with a performance issue. In my parent React component, I make the API call in componentDidMount and pass this object to child compo ...

How can a mock document be utilized in a unit test for an imported TypeScript dependency?

To effectively unit-test a legacy TypeScript class, I am seeking ways to mock the document object. The class has dependencies on another class (View.ts), which in turn relies on a 3rd party module that further depends on the existence of the document. The ...

What causes an ObjectUnsubscribedError to be triggered when removing and then re-adding a child component in Angular?

Within a parent component, there is a list: items: SomeType; The values of this list are obtained from a service: this.someService.items$.subscribe(items => { this.items = items; }); At some point, the list is updated with new criteria: this.some ...

Initiate and terminate server using supertest

I've developed a server class that looks like this: import express, { Request, Response } from 'express'; export default class Server { server: any; exp: any; constructor() { this.exp = express(); this.exp.get('/' ...

The assessment of expression ___ has been altered following its examination

What could be causing the component in this straightforward plunk to throw an error? @Component({ selector: 'my-app', template: `<div>I'm {{message}} </div>`, }) export class App { message:string = 'loading :('; ...

Issue with BehaviorSubject<Object[]> causing incorrect array data upon initial subscription

I am facing an issue with a BehaviorSubject where the first .subscribe callback is returning an Array with 6 Objects. Strangely, in console output, it shows length: 6, but every for-loop I iterate through the array only runs 5 times and even when I log arr ...

Ways to transfer data from TypeScript to CSS within Angular 6

Trying to work with ngClass or ngStyle, but I'm struggling with passing the value. Here's my current code: strip.component.ts import { ... } from '@angular/core'; @Component({ selector: 'app-strip', templateUrl: &apo ...

Creating a custom extended version of Angular2 Http does not automatically provide injection of services

I'm struggling to understand this issue. I've created a custom class that extends Angular's Http class. import { Injectable } from '@angular/core'; { Http, ConnectionBackend, RequestOptions, RequestOptionsArgs, ...

Switching Next.js JavaScript code to Typescript

I am currently in the process of transforming my existing JavaScript code to TypeScript for a web application that I'm developing using Next.Js Here is the converted code: 'use client' import React, { useState, ChangeEvent, FormEvent } fro ...

Calculate the total of JSON objects while eliminating duplicates in an array

Below is an array of objects: const lineItems = [ { "lineNumber": "0", "item": "1496", "itemDesc": "wertyuiasdfghj", "qualityReceiptHold": "N", ...

Changing the time in Angular while converting a string to a date object has proven to be

Can anyone help me with a problem I'm having trying to convert a String into a Date object without it being affected by timezone changes? Specifically, when I receive 2020-07-14T15:27:39Z from an http get request, I need to convert this into a Date o ...

Removing special characters when pasting into text box in Angular 2 or higher versions

To ensure that special characters are trimmed or removed when pasting into a textbox inside the TypeScript component file (with extension .ts), utilize a function within the TypeScript component itself. The modified text should be displayed in the textbox ...

Breaking down nested arrays in typescript

After receiving a response from the service, the data included the following: "rows": [ [ "stravi/aa", "202001", "59", "51", "2558.98", "0.5358894453719162", "1.9204668112983725", "140", "2.346630 ...

Exploring Angular 4's Capabilities: Navigating a Multi-Dimensional Array

I am currently working with a multi-dimensional array that has two keys, and it is structured as follows: user: any = {}; // The index is incremented within a for loop to add values to the user object (this part is functioning correctly) this.user[index++ ...

Tips for showcasing styled text in Vue using API data

I'm having trouble formatting text in Vue. Within a component, I have a textarea that stores a string with backspaces, etc ... in an API like this: A cellar but not only...\n\nWelcome to the Nature & Wine cellar, a true Ali-baba's cave ...

Having Trouble Importing a Dependency in TypeScript

My experience with using node js and typescript is limited. I attempted to include the Paytm dependency by executing the following code: npm install paytmchecksum or by inserting the following code in package.json "dependencies": { ... & ...

Encountered an issue with the Dynamic Form: TypeError - The property 'value' is undefined and cannot be read

RESOLVED An incorrect value was causing an issue with the onChange function. public onChange = (e:any, key:any) => { this.setState({ [key]: e.target.value }); }; I'm struggling to resolve an error while inputting data into my form in T ...

Customizing the text color of words that originated from a dropdown selection within an Angular textarea editor

My Process: Within my interface, I utilize both a dropdown menu and a textarea field. I input text into the textarea and select certain words from the dropdown menu to add to the textarea. I have successfully completed this task. The Issue at Hand: Now, ...

The (change) function is triggered when there is a modification in the parent object of ngModel within Angular 2

When the (change) function on element is triggered with the parent object of ngModel change in Angular 2, this is how I assigned the model: (change)="OnScheduleChange(confirmSchedule)" [(ngModel)]="AddMedMod.schedule.numberOfDaysOn" Now, whenever I make ...

Utilizing Ramda lenses for composition in Typescript with the useState set function in React

I am currently learning functional programming and exploring event handling in React. Let's consider the following example: interface Todo { task: string done: boolean } interface TodoProps { todo: Todo onChange: ChangeEventHandler< ...