Examining the array to ensure the object exists before making any updates in the redux

Is there a way to determine if an object exists in an array and update it accordingly?

I attempted to use the find method, but it couldn't locate the specified object. I also tried includes, but it seems to be unable to recognize the item within the array.

This is my current approach:

import { createSlice, PayloadAction } from "@reduxjs/toolkit";

interface Displate {
  name: string;
  finish: string;
  size: string;
  frame: string;
  price: number;
  quantity: number;
}

interface DisplateArray extends Array<Displate> {}

const initialState: DisplateArray = [];

export const cartSlice = createSlice({
  name: "cart",
  initialState,
  reducers: {
    addDisplate: (state, action: PayloadAction<Displate>) => {
      state.map((displate) => {
        if (displate.name === action.payload.name) {
          return displate.quantity++;
        } else {
          return state.push(action.payload);
        }
      });
    },
  },
});

export const { addDisplate } = cartSlice.actions;

export default cartSlice.reducer;

However, this implementation adds a new object every time.

Answer №1

It appears that the quantity is not being properly updated due to the fact that state.map does not reflect the changes made to the quantity in the proxy state.

If your objective is to verify if an item with the same name already exists in the state array, and then either increment its quantity by 1 or add a new object from action.payload to the array, consider using find as a condition (and utilizing Immer for updating in Redux Toolkit):

export const cartSlice = createSlice({
  name: "cart",
  initialState,
  reducers: {
    addDisplate: (state, action: PayloadAction<Displate>) => {
      const existingItem = state.find(
        (item) => item.name === action.payload.name
      );
      if (!existingItem) {
        state.push({ ...action.payload, quantity: 1 });
        return;
      }
      existingItem.quantity++;
    },
  },
});

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

I'm curious, which ref tag should I utilize for draft.js?

I'm currently working on a form using Draft.js with Next.js and TS, but I've encountered some errors in my code. Here is what I have so far: import {Editor, EditorState} from 'draft-js'; const [editorState, setEditorState] = useState( ...

How can I render nested routes separately from the parent route in React Router?

Creating a shopping page with products displayed, I want the router to render the product page with all the details when a user clicks on a product. The routing setup looks like this: <BrowserRouter> <Routes> <Route path="/&q ...

Having trouble with a 404 error on form submission with React and Express?

I am currently working on a basic MERN application. My goal is to establish a connection between the front and back ends in order to post data on the server upon form submission. While I can access the server URL directly, I encounter a 404 error (Not Foun ...

Is it possible to integrate the Firestore npm library into my Express application?

Recently, I created my own library to act as a nosql database on my node.js web server in place of mongodb. I came across this interesting quote: Applications that use Google's Server SDKs should not be used in end-user environments, such as on pho ...

Incorporate communication between the front-end and backend

I encountered an error while attempting to import the getUser function in my backend code. The actual function is located in the frontend at ../utils/auth. How can I successfully import between front-end and backend? Or might there be another issue at pla ...

Transmit a form containing a downloaded file through an HTTP request

I am facing an issue with sending an email form and an input file to my server. Despite no errors in the console, I can't seem to upload the file correctly as an attachment in the email. post(f: NgForm) { const email = f.value; const headers = ...

Tips for optimizing your website design with Box layouts

I'm currently working on a web application using React along with Material UI. My objective is to create a layout that consists of two Boxes nested within a third Box. The bottom Box should adjust its height based on its content, while the top Box nee ...

Is the return type of 'void' being overlooked in TypeScript - a solution to avoid unresolved promises?

When working in TypeScript 3.9.7, the compiler is not concerned with the following code: const someFn: () => void = () => 123; After stumbling upon this answer, it became apparent that this behavior is intentional. The rationale behind it makes sens ...

Adjust the width of the lower drawer component using React

After some extensive searching, I've hit a roadblock trying to tweak the width of an imported Material UI Drawer Swipeable edge. My aim was to make it Bottom-type without spanning the entire screen. I managed to adjust the top width using sx. However ...

Is it necessary to conceal Angular navigation controls when the user is not authenticated?

In Angular, is there a standardized method for hiding controls when the user is not logged in? We already have the CanActivate guard which checks if a user can access a route. Would it be better to hide the route initially if the user is not logged in or l ...

Context-aware background imagery

I am facing an issue with displaying pictures in the background on my webpage. The problem I encountered is that sometimes my API does not provide images to display, so I want to set a condition to show another picture instead. However, I am unsure wheth ...

Unleashing the power of eventListeners through exponential re-rendering upon state updates

Trying to implement an eventListener for "keydown" to update the state (a boolean named showMenu). I placed it inside a useEffect, but it's not functioning correctly and I can't pinpoint the issue. When I include showMenu in the dependency arra ...

What are some potential causes of webpack-dev-server's hot reload feature not working properly?

Having an issue with my React project. When I try to use hot reload by running "npm start" or "yarn start" with webpack-dev-server configured (--hot flag), I'm getting the error message: [error message here]. Can anyone assist me in troubleshooting th ...

Oops! You can only have one parent element in JSX expressions

I'm working on creating a password input box, but I keep encountering an error when integrating it into my JS code. Here's the snippet of my code that includes TailwindCSS: function HomePage() { return ( <div> <p className=&q ...

The v-text-field within the activator slot of the v-menu mysteriously vanishes upon navigating to a new route within a

Working on my Nuxt project with Vuetify, I encountered an issue where the v-text-field would disappear before the page changed after a user inputs date and clicks save. This seems to be related to route changing, but I have yet to find a suitable solutio ...

What is the best way to define the height of a Dialog in Material-UI?

Exploring the Material-UI example, I discovered a way to customize the width of a Dialog: const customContentStyle = { width: '100%', maxWidth: 'none', }; // some omitted code <Dialog title="Dialog With Custom Width" ...

Is there a way to ensure that the line numbers displayed for JavaScript errors in Chrome are accurate?

I suspect either my webpack configuration or my npm run dev script are causing the issue, but I'm unsure of what exactly is going wrong. While running my application in development mode, I encounter error messages like: Uncaught TypeError: this.props ...

Syncing data between local storage and a remote server using Ionic5 provider

I've been considering implementing a data provider that could store a duplicate of the backend data locally for quick access. I believe this concept is referred to as mirroring or something similar. Nevertheless, it must be synchronized and updated r ...

Each time my classes are initialized, their components undergo reinitialization

Apologies if the question is not well-formed, I am completely new to working with React. I have been attempting to create a dashboard but encountering issues with my states getting reinitialized. Below is the content of my app.js file. import './inde ...

Having trouble adding state values to an object

I have a specific state set up in my class: this.state = { inputValue: "", todos: [] } My issue lies within an arrow function where I am attempting to use setState to transfer the value of inputValue into todos. this.setState({ inputValue: & ...