The field 'user' is not recognized on the object type WritableDraft

I've set up a redux userSlice to retrieve user data from the store.

client/src/redux/features/userSlice.ts

import { createAsyncThunk, createSlice, PayloadAction } from "@reduxjs/toolkit";
import { User } from "../../interfaces/user";
import userApi from "../../apis/user";

export const getUser = createAsyncThunk("user/getUser", async (_, thunkApi) => {
  try {
    const response = await userApi.getUser();
    return response;
  } catch (error) {
    throw thunkApi.rejectWithValue({ error: "user not initialized" });
  }
});

const userSlice = createSlice({
  name: "user",
  initialState: {
    profile: {
      ipAddress: "",
    },
  },
  reducers: {
    getUser: (state, action: PayloadAction<User>) => {
      state.user = action.payload;
    },
  },
});

export const { getUser: getUserAction } = userSlice.actions;
export default userSlice.reducer;

The user data is successfully logged out in the API interface:

client/src/apis/user.ts

const userApi = {
  getUser: async () => {
    try {
      const response = await fetch("http://localhost:5000/user/:ipAddress");
      const user = await response.json();
      console.log("in user api:", user);
      return user;
    } catch (error) {
      console.error("Error fetching user:", error);
      return error;
    }
  },
};

export default userApi;

console.log("in user api:", user);
displays the following:

in user api: 
Object { user: {…} }
​
user: Object { _id: "65c1f831b5759dc19442396d", ipAddress: "::ffff:127.0.0.1", createdAt: "2024-02-06T09:13:21.391Z", … }
​
<prototype>: Object { … }

However, I'm encountering an error on state.user = action.payload stating

Property 'user' does not exist on type 'WritableDraft<{ profile: { ipAddress: string; }; }>'

The defined user types are as follows:

client/src/interfaces/user.ts

export type User = {
  profile: UserProfile
}

export type UserProfile = {
  ipAddress: string
}

export type UserState = {
  user: User
}

My redux state only shows the initial state being fulfilled, without the user's ipAddress as expected.

https://i.sstatic.net/AY9Kg.png

Answer №1

In the userSlice state, there is no property called user. The userSlice state actually represents a type of User. If the function getUser is meant to set the "user", it should replace the state entirely. Instead of assigning action.payload directly to state = action.payload, you should return action.payload as reassigning the draft state is not valid.

Here's an example:

const initialState: User = {
  profile: { ipAddress: "" },
};

const userSlice = createSlice({
  name: "user",
  initialState,
  reducers: {
    getUser: (state, action: PayloadAction<User>) => {
      return action.payload; // Return the User value here
    },
  },
});

Answer №2

It appears that there may be an issue with the WritableDraft interface you are using. Can you please provide more information about how this interface is defined in your question? It seems like there might be some confusion between the WritableDraft attribute and the user attribute.

Here is a suggested update:

const userSlice = createSlice({
  name: "user",
  initialState: {
    profile: {
      ipAddress: "",
    },
  },
  reducers: {
    getUser: (state, action: PayloadAction<User>) => {
      // Make sure to update the profile attribute, not the user attribute
      state.profile = action.payload;
    },
  },
});

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

Change an ISO date format to DD:MM:YYYY HH:MM using Angular

I currently have my date in this format: 2022-11-21T21:07:56.830-07:00 However, I am looking to convert it to the following format: 21/11/2022 07:56 ...

Is there a way to expand the return type of a parent class's methods using an object

Currently, I am enhancing a class by adding a serialize method. My goal is for this new method to perform the same functionality as its parent class but with some additional keys added. export declare class Parent { serialize(): { x: number; ...

Make sure to always include a trailing comma when defining a single type parameter T. Here's an example: `<T,>`

Ensure that a single type parameter T includes a trailing comma. For example: <T,>. (3:29) export const toggleItem = <T>( How can I resolve this error? Adding <T,> causes Prettier to remove the "," when saving. I have not made any change ...

Incorporating Moralis into Ionic Angular with TypeScript

I'm currently developing an app using Ionic Angular (TypeScript) that will be compatible with both Android and iOS devices. I've decided to incorporate the Moralis SDK to establish a connection with the Metamask wallet. Here's a summary of ...

When using Angular, the Zone can be accessed through VSCode intelligence, but it appears as undefined when running in

Upon attempting to utilize Zone within the ngOnInit function in my Angular application, I placed a breakpoint on line 11. However, when inspecting the function Zone(parent, zoneSpec){....}, it returns undefined upon launching in Chrome browser. Here is the ...

The functionality of CDK Drag Drop is not accurately adjusting the placement of images

I have implemented an image gallery and am working on rearranging the position of the images using the Drag & Drop cdk library. However, I am facing an issue where the swapping of images does not always occur correctly; sometimes when attempting to exchan ...

Tips for toggling visibility in Angular 2

I utilized [hidden] in the following way where the value of "secondTab" is set to true. <form #siteForm="ngForm" novalidate (ngSubmit)="saveSite(siteForm.value,siteForm.valid)" class="admin-modal"> <div class="txt-danger">{{errorMessage}}&l ...

Setting up the propTypes for interface in React TypeScript

How can I specify the correct PropTypes for a property that is an interface in TypeScript with PropTypes? Requirements - Implementing both TS and PropTypes. Goal - To have a more precise type definition than PropTypes.any that meets standard eslint an ...

The type of undefined cannot be assigned to the specified type

I am currently working on implementing a pie chart (donut series) in Angular. Below are my HTML, CSS, and TypeScript files. I am following this tutorial resource: Link to CodeSandBox - https://codesandbox.io/s/apx-donut-simple-8fnji?from-embed import ...

Implement a T3 App Redirect in a TRPC middleware for unsigned users

Is there a way to implement a server-side redirect if a user who is signed in has not finished filling out their profile page? const enforceUserIsAuthed = t.middleware(({ ctx, next }) => { if (!ctx.session || !ctx.session.user) { throw new TRPCE ...

Preventing text from wrapping in a TypeScript-generated form: Tips and tricks

I’m currently working on a ReactJS project and my objective is simple: I want all three <FormItem> components to be displayed in a single line without wrapping. However, I am facing the following output: https://i.stack.imgur.com/mxiIE.png Within ...

Is TypeScript declaration merging not functioning properly?

Trying to enhance an existing interface with a new member is causing Typescript errors for me. // foo.js export interface IOption { xOffset: number } import {IOption} from 'foo'; // Attempting to extend IOption with `yOffset`, but encounter ...

Explain the object type that is returned when a function accepts either an array of object keys or an object filled with string values

I've written a function called getParameters that can take either an array of parameter names or an object as input. The purpose of this function is to fetch parameter values based on the provided parameter names and return them in a key-value object ...

After I subscribe, why do the variables of my object become undefined?

Just starting out with Angular and using Angular9. I attempted to subscribe to an observable in the following code: I have a service that makes an HTTP request and returns an Observable. The subscription appears to be working fine. ngOnInit() { this.in ...

Incorporating a d3 chart into an Angular 4 project

Currently, I am in the process of developing an Angular application using TypeScript. My aim is to incorporate a force directed network graph from Mike Boston built with d3, which can be viewed here. After successfully translating most of the code to Type ...

The use of 'import ... =' is restricted to TypeScript files

Error: Oops! Looks like there's a hiccup in the code... 'import ... =' is exclusive to TypeScript files. Expecting '=' here. Don't forget the ';'. Unexpected keyword or identifier popping up! package.json ...

Verification of unique custom string

How can I ensure that a string follows the specific format of x.xx.xxxxx? The first character is mandatory, followed by a period, then two characters, another period, and finally any number of characters of varying lengths. ...

React Typescript - Unexpected character ',' encountered at line 1005

Currently, I am utilizing Typescript within a React application that integrates with Graphql. Encountering an error: ',' expected.ts(1005) After researching possible solutions, most suggest that the issue might be due to using an outdated ve ...

What is the best way to create a jumping animation for an object in Cannon.js and Three.js?

During my quest for a solution, I came across a common practice where users used cannonBody.velocity.y = JUMP_VELOCITY to make an object jump. However, in my scenario, this method only worked while the object was already in motion and not when it was stat ...

The utilization of functions from a implemented interface results in the generation of a 'non-function' error

I recently created an interface that includes variables and a function. However, I encountered an issue when trying to utilize the implemented function for a specific class as it resulted in an 'ERROR TypeError: ...getPrice is not a function" Below ...