How to update a ReactJS component based on changing values

As a user, I have a wishlist feature on my website. Whenever I add items to my wishlist, they are stored in the localStorage. I also want to display the total number of items in my wishlist automatically without having to refresh the page.

Although the items are successfully added to the wishlist and displayed in the span tag, I encounter an issue in the console: Warning - Maximum update depth exceeded.

If anyone can provide assistance with this issue, it would be greatly appreciated. The code for this functionality is located in the Header component of the page.

/* Code for the Header component */

import React, { useContext, useState, useEffect } from 'react';
import { Container, Navbar, Nav } from 'react-bootstrap';
import { ThemeContext } from '../GlobalComponents/ThemeProvider';
import { BiSun, BiMoon, BiCart } from 'react-icons/bi';
// Other imports...

// Component definition...

In addition to the Header component, there is also a ProductCard page included below:

/* Code for the ProductCard component */

import React, { useState } from 'react';
import { Button, Card } from 'react-bootstrap';
import { useThemeHook } from '../GlobalComponents/ThemeProvider';
import { useCart } from 'react-use-cart';
import { BsCartPlus } from 'react-icons/bs';
// Other imports...

// Component definition...

Answer №1

It seems like the warning you're encountering is due to an infinite loop caused by listening to and updating the same state.

To resolve this, consider updating your count state only when the "Add to wishlist" button is clicked. After adding a new item to the existing wishlist stored in the count state, the useEffect function will automatically sync the updated wishlist with the local storage.

export default function App() {
  // Pull wishlist items from localstorage and set them in state as initial state
  const [count, setCount] = useState(JSON.parse(localStorage.getItem("liked")) || []);

  // Function to add an item to the wishlist
  const addToWishlist = (item) => {
    setCount(prev => [...prev, item]);
  };

  // Update localstorage whenever the state changes
  useEffect(() => {
    localStorage.setItem("liked", JSON.stringify(count));
  }, [count]);

  return (
    <div>
      <h1>Wishlist</h1>
      <h2>{count.length}</h2>
      <button onClick={() => addToWishlist({id: 1, name: 'test'})}>Add to Wishlist</button>
    </div>
  );
}

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

Determine the character count of the text within an *ngFor loop

I am a beginner in Angular (8) and I am trying to determine the length of the input value that I have created using a *ngFor loop as shown below: <div *ngFor="let panel of panels; index as i" class="panel" [id]="'panel-' + panel.id"> & ...

Having trouble with React Testing Library throwing an error every time I try to use fireEvent on an input text?

When attempting to utilize the "fireEvent" method from React Testing Library, I encountered an error as shown below: https://i.sstatic.net/ExH4u.png MainSection.test.js: test('Verifying SearchBar functionality', async () => { render(< ...

Looking to include an if/then statement for an item that has been generated within a div?

While I may not be a seasoned programmer, I am facing an issue that requires some problem-solving. Allow me to explain the situation to the best of my ability. Within a "div" element, I have implemented a v-for loop that sets a value in a variable for dis ...

Discover the white circle search bar display

I am attempting to implement a circular reveal animation to display the search toolbar in my web application using CSS and JavaScript. My goal is to achieve a similar effect as seen on Whatsapp for Android. https://i.sstatic.net/YE242.jpg I have successfu ...

Troubleshooting: Issue with XMLHTTPrequest functionality

I am attempting to make a request to a service using two different methods 1) Using XMLHTTPRequest -> Currently not functioning correctly Error message: JSON.parse unexpected end of data in line 1 col 1 function createCORSRequest(method, url) { ...

Guide to customizing margins at specific breakpoints in Bootstrap 4 without using javascript

Despite exploring numerous solutions and trying them out, I have yet to achieve the desired results. I am looking to customize margins for various breakpoints in Bootstrap. For example: View for laptops, Tablet view The issue may be related to defined w ...

Form validation in AngularJS for controllers with multiple instances

My specific needs In order to meet the unique requirements of my business, manual validation is necessary. The validation rules can vary in strictness depending on the context in which a specific screen is accessed. It is also important to note that ther ...

What is the best way to handle multiple requests to the same URL in Cypress while waiting?

I am currently developing a Cypress test that involves sending multiple requests to the same URL with varying body content. Essentially, the test modifies input values in the user interface, triggering new server requests. The challenge arises when trying ...

Obtain the file path and store it in a variable right after using fs.writefile

Can anyone assist me in obtaining the file path of the created file in the following code snippet? I am passing a barcodeSourceNumber as a parameter and expecting the file path as the return value. pathToFile = generateBarcodeImage('123456789'); ...

The scatterplot dots in d3 do not appear to be displaying

My experience with d3 is limited, and I mostly work with Javascript and jQuery sporadically. I am attempting to build a basic scatterplot with a slider in d3 using jQuery. The goal of the slider is to choose the dataset for plotting. I have a JSON object ...

Exploring ways to programmatically include questions in the meta.js file of a Vue Webpack template

I have made a customized version of the Vue Webpack template and am currently modifying the meta.js file. I am attempting to figure out how to include a new property in prompts as shown below: "pages": { "type": "input", "required": true, ...

What is the reason for the 'admin' page not being displayed?

After reading the MEAN MACHINE Book and following the instructions on Routing Node applications [pg - 36], I encountered an issue. The express.Router()⁴⁸ functions as a mini application where you can define routes. Let's see an example by adding ...

Steps for positioning an element to the left and center of a div

I'm having trouble aligning my two elements in a simple horizontal menu to the middle left. I want them to have a margin of 5px on the left and right sides. Here is a screenshot and CSS style: https://i.stack.imgur.com/vzO5D.png .body_clr { wid ...

What is the best way to declare variables in an HTML document that can be accessed by an external JavaScript file when including the JavaScript code in the HTML?

Issue at Hand: In my attempt to streamline the process, I have encountered a problem. Everything works perfectly when I embed the JavaScript code in each HTML file and manually input all the variables. However, when I attempt to bundle it up as follows, it ...

Upgrade the arrow accordion in bootstrap by incorporating images instead

I have implemented a Bootstrap accordion with a toggle arrow. Here is an example: http://jsfiddle.net/zessx/r6eaw/12/ My question is, if I want to change the arrow with an image, what do I need to edit? Or how can I implement it? This is the image I want ...

Menu: animated opening/closingIs this convenient, or

How can I add animation to opening and closing menu items in my project? I am not sure if it can be done in Angular or CSS. I have provided a reproduction of the project for reference => Stackblitz. HTML file <div class="wrapper"> & ...

Managing the position of the caret within a content-editable div

I need help with editing a contenteditable div in HTML <div contenteditable="true" id="TextOnlyPage"></div> Here is my jQuery code: var rxp = new RegExp("(([0-9]+\.?[0-9]+)|([0-9]+))", "gm"); $('#TextOnlyPage').keyup(function( ...

What could be causing this error with creating an order on Paypal?

Every time I run this code and click the Paypal button, I encounter the following error: Error: "TypeError: Cannot read property 'map' Do you have any clue why this is happening? I am pretty sure that I formatted it correctly. (I replaced MY_C ...

Improving the functionality of dynamically updating server-side rendered props

I have posts with comments and I would like to create a post view that displays all the comments for that post. In my implementation, the getServerSideProps function passes the entire post (including comments) to the page. My goal is to dynamically update ...

The package.json dependency is failing to update from ^0.0.130 to ^0.0.145 despite 1.0.145 being the most recent version available

Within the package.json file for my reactjs webpack project, I denoted a dependency's version number as ^0.0.130 when running npm install, despite knowing that the latest available version is 0.0.145. To my surprise, the installation process retrieve ...