What could be causing the error in my ngrx parameter?

I have a service that handles user sign-ups, as shown below:

public signup = (user:UserModel) => {
    console.log('UserService.user', user)

    return this.httpClient.post<{user:UserModel}>(this.url, {user}).pipe(
      tap(user => {
        console.log('UserService.user tap', user)
        this.store.dispatch(StoreUser({user}))
      })
   )
 }

When trying to dispatch the received user data to the StoreUser action, I encountered an error. There seems to be a type mismatch in the parameter 'user' in this line

this.store.dispatch(StoreUser({user})
, indicated by a red underline. The specific error message is:

Type '{ user: UserModel; }' is missing the following properties from type 'UserModel': firstName, lastName, password, email, tokents(2739) user.actions.ts(6, 13): The expected type comes from property 'user' which is declared here on type '{ user: UserModel; }' (property) user: UserModel

Here is the structure of the UserModel class:

export class UserModel {
    public firstName:string = '';
    public lastName:string = '';
    public password:string = '';
    public email:string = '';
    public token:string = '';
}

This is the definition of the action 'StoreUser' :

import { createAction, props } from "@ngrx/store";
import { UserModel } from "./user.model";

export const StoreUser = createAction(
    '[Store user] Store user',
    props<{ user:UserModel }>()
  );

Answer №1

It appears that the user within the context of tap is expected to be of type { user: UserModel }.

If this is the case, then it could be either in the format of tap(({ user }) => ...) (using curly braces around user), or possibly similar to the following example:

tap(response => {
  const user = response.user
  console.log('UserService.user tap', user)
  this.store.dispatch(StoreUser({user}))
})

Answer №2

When implementing the solution suggested by Tortila, it is important to ensure that the curly braces around the user property are removed when calling the action. This will help avoid any type mismatch issues. The Action expects a type of { user: Model}. If you mistakenly include extra curly braces around the user property like so {{user: UserModel}}, it can lead to a type mismatch error because it changes the expected type. Expected type: {user: UserModel} Your provided type: {{user: UserModel}}

...
    return this.httpClient.post<{ user: UserModel }>(this.url, {user}).pipe(
      tap((user) => {
        console.log('UserService.user tap', user)
        this.store.dispatch(storeUserAction(user))
      })
    )

Answer №3

function login(user:UserModel) {
    return this.httpClient.put<UserModel>(this.url, {user}).pipe(
        tap(user => {
            console.log('UserService.user tap: ', user)
            this.store.dispatch(StoreUser({user: user}))
        }),
        catchError(error => {
            console.log('error', error)
            this.toastr.warning(error.error, '');
            throw error;
        })    
    )
}

}

Model:

export class UserModel {
    public firstName?:string;
    public lastName?:string;
    public password?:string;
    public email?:string;
    public token?:string;
}

Action:

export const StoreUser = createAction(
'[Store user] Store user',
props<{ user:UserModel}>()

);

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

It is important to utilize the toHaveBeenCalledTimes method

I am currently working on an assertion involving the method toHaveBeenCalledWith In your opinion, is it crucial to also assert the toHaveBeenCalledTimes(1) Appreciate your input, ...

Need to end all Node.js instances to properly reflect the code. Any solutions for resolving this issue?

After developing an application using typescript, hapi, and nodejs, I encountered a strange issue. Whenever I save, remove, or add new code, the changes are not reflected even after running gulp build. The only way to get it working is by closing all run ...

What is the proper way to incorporate types in a universal function?

Encountering an issue with TypeScript while using a universal function export const createNewArray = <T>( arr: T[], keyId: keyof T, keyTitle: keyof T, ) : [] | TValue[] => { const arrayAfterMap = arr.map((item) => ({name: item[ ...

The use of supportedChain is no longer recommended, networks should be passed instead

As I reach the final lesson, an error message appears in my localhost console: The 'supportedChain' is deprecated, please pass networks instead useConfig @ context.ts:23 Initially, I suspected it was a problem with my code. However, even after c ...

Navigating with dynamic angular2 routes?

I'm looking to redirect to another component using the path provided, but I also need to pass along the variable this.a. How can I accomplish this so that I can access the value of this variable in the other component? Component.ts import {Componen ...

Can you retrieve the form control names in an array within an Angular reactive form?

<div *ngFor="let response of responsesForm?.get('responses')?.value; let i = index;"> <div [innerHTML]="response.content"></div> <textarea formControlName="response.content"></texta ...

What is the best way to include a Typescript declaration for a Knockout extender that enhances the functionality of an observable by adding additional

I am facing a challenge with incorporating a knockout extender into a typescript file, struggling to properly declare it. The extender is in javascript, and I need to utilize it from within a typescript file (as the project consists of both javascript and ...

Conditional Types - Finding the perfect match for a nullable type

I am attempting to find a nullable type in a conditional type: interface Unwrapped { dummyProp: string; } interface UnwrappedArray<T extends Unwrapped> extends Array<T> { } interface Wrapped<T extends Unwrapped> { unwrapped: T; } type T ...

Clearing the filename in a file type input field using React

When using this input field, only video files are accepted. If any other types of files are uploaded by enabling the "all files" option, an alert will be displayed. While this functionality is working correctly, a problem arises if a non-video file is adde ...

What is the best way to utilize a tsconfig "alias path" to import an @ngModule along with other definitions?

Repository Link: https://github.com/andreElrico/mono-repo-test Stackblitz Example: https://stackblitz.com/github/andreElrico/mono-repo-test (noop; only to navigate smoothly) Assume the structure below: root/ ├── projects/ │ ├── app1 │ ...

Having issues with your Typescript in Sublime Text?

The issue with the TypeScript plugin in Sublime Text (version 3126) suddenly arose without any identifiable cause. It seems that the plugin no longer recognizes types, resulting in disabled error highlights and autocompletions. This problem occurred on M ...

Transferring data from an Angular 2 component to a service

I am trying to pass data from an Angular component to a service and utilize the service's methods to manipulate it. Here is an example: class SomeComponent { public info: Array<any> = MyData; constructor(private myService: TablePag ...

Tips for closing Angular Material Sidenav using the escape key

I am attempting to automatically close the Angular Material Sidenav by pressing the escape key. Despite my efforts to use the [autoFocus]="true" property, I have not been successful in achieving this functionality. The issue lies in the fact that pressin ...

Mastering the Application of useSelector with TypeScript

I am using the useSelector code snippet below: const user = useSelector<RootStateOrAny, typeof typeRootReducer>((state) => state.user) This is how it looks in the rootReducer: const rootReducer = combineReducers({ user: userReducer }) exp ...

Mastering the Art of Mocking Asynchronous Methods in Node.js Using Jest

I have the following files: |_ utils.js |_methods.js I am currently conducting unit testing for rest.js methods, where the content of the file is as follows: methods.js import Express from 'express' import { add_rec } from './utils' ...

Solving Cross-Origin Request Sharing (CORS) Problem in

Encountered a CORS issue while attempting to send a post request to a C# web API. Here is the error message: Access to XMLHttpRequest at 'api url in different domain' from origin 'client url' has been blocked by CORS policy: Respon ...

"Looking to incorporate dynamic Carousel Indicators into your Angular2 project? Here's how you can

After moving to just one slide, the "next" and "prev" buttons stop working. Additionally, clicking on the indicators to move slides is also ineffective. Interestingly, when I remove the div with the class carousel-indicators, the "next" and "prev" buttons ...

Encountering a 404 error while attempting to test a contact form on a Next.js website using a local server

Trying to test a contact form in Next.js where the data is logged but not sent to the API due to an error. "POST http://localhost:3000/app/(pages)/api/contact/route.tsx 404 (Not Found)" Troubleshooting to identify the issue. [directory setup] ...

In the latest version of Expo SDK 37, the update to [email protected] has caused a malfunction in the onShouldStartLoadWithRequest feature when handling unknown deeplinks

After updating to Expo SDK 37, my original code that was previously functioning started encountering issues with <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0e7c6b6f6d7a23606f7a67786b23796b6c78667f79627a">[email prot ...

How can I retrieve the index of an element within a 2D array using JavaScript when the array is displayed on a webpage?

https://i.stack.imgur.com/GHx9p.png I am currently working on developing an Othello game board within an HTML page using Angular. The board itself is constructed from a 2D number array which I then display using the <table> tag on the webpage. Below ...