Rendering in ReactJS can be executed by updating the value and triggering a re

I am currently working on an ecommerce project where I have a wishlist feature. When adding items to my wishlist, they are stored in the localStorage. Now, I want to display the total number of items in my wishlist, but I am unsure how to automatically update the header when the value in the localStorage changes.

I have added a button that triggers a function called 'cou' upon clicking. However, when I add items to the wishlist, the header does not render the updated count. Strangely, when I click the button, everything works perfectly fine.

const [count, setCount] = useState((JSON.parse(localStorage.getItem("liked"))));

  const cou = () => {
    let oldData = JSON.parse(localStorage.getItem('liked') || "[]")
    if (oldData.length === count.length) {
      setCount((JSON.parse(localStorage.getItem("liked"))))
    } else {
      setCount((JSON.parse(localStorage.getItem("liked"))))
    }
  };

  useEffect(() => {
    let oldData = JSON.parse(localStorage.getItem('liked') || "[]")
    if (oldData.length === count.length) {
      setCount((JSON.parse(localStorage.getItem("liked"))))
    } else {
      setCount((JSON.parse(localStorage.getItem("liked"))))
    }
  }, [(count.length)]);

This span element is located in the header:

<span style={{ position: 'relative', left: '-21px', top: '-18px' }}>{count.length}</span>}

Answer №1

Could you verify the output by using [count] instead of [(count.length)]? I am interested to see the result.

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

Everything seems to be functioning properly on the local server, but once the media files or players (mp3 and mp4) are uploaded, the background fails to work entirely

function playMusic() { var songs = [ "pump.mp3", "ybwm.mp3", "bb.mp3", ]; var randomIndex = Math.floor(Math.random() * songs.length); var selectedSong = songs[randomIndex]; var audio = new Audio(selecte ...

Why doesn't "align-self: flex-end" relocate the game board to the bottom of the screen?

Hey there, I am currently working on developing a Connect 4 game and have decided to use a table for the board. To position the board properly, I am utilizing flexbox. Although I have specified align-items as 'flex-end' in order to bring it to th ...

A guide on testing the output of a child component within a parent component using react testing library

Due to restrictions, the original code cannot be posted here. However, I will provide an explanation of what I am trying to accomplish. In my project, there is a component that displays a message. This message is part of a child component that is rendered ...

Python: Utilizing HTML User Input to Search Database

I am currently working on a project that involves searching a database using HTML. Here is the code snippet I am using: <form action="/question/search" method="POST"> <input id="search" type="text" placeholder="Search.." name="s ...

How to programmatically set checkbox in Angular 4

Despite reading similar questions, I am still struggling to understand the issue. My component receives a list of items Array<{id: number, name: string}> and a list of "checked" items Array<number> @Component({ selector: 'check-list&a ...

Delaying Jquery on scroll Event

Hey there, I've got a set of icons that I'd like to reveal one by one as you scroll down. I've incorporated some animations from , but now I'm wondering how I can implement a delay function in my jQuery so the icons appear sequentially ...

Deleting an element from an HTML page with jQuery

Hi there, I'm just starting to learn about jQuery. Below is an example of a list element I have: <ul> <li> <a href="abc">ABC</a> </li> <li> <!-- This is the element I want to get rid of --&g ...

Utilizing ReactJs to Generate a Random Number for Visualization in a Material UI Progress Bar

I am looking to generate a random number for my test functionality in order to display it within a Material UI Progress bar. I have successfully implemented this piece of JavaScript code on JSFiddle, but now I want to integrate it into my React application ...

Sending an AJAX request to a PHP file to retrieve data in JSON format

Greetings everyone, I am currently exploring the world of AJAX for sending information to a JSON file and I'm unsure about the structure of the .php file needed to process it. My experience with .php is quite limited. Can anyone guide me in the right ...

Angular: mysterious 'null!' syntax

As I delved into the Angular 2 source code, my curiosity was piqued by NgForOfContext<T>, located in the official repository here. What caught my attention was a particular syntax that seemed unfamiliar to me in both plain Javascript and Typescript. ...

Is it possible for AJAX and PHP to collaborate seamlessly?

Currently, I'm facing an issue where my Js file is failing to recognize a php variable that is generated by ajax. Let's take a look at the structure: index.php: <script src="js.js"> </script> <? include('build.php'); &l ...

Adding up and finding the contrast between odd and even numbers

After successfully segregating the odd and even numbers, I am faced with a challenge in determining how to add the odds together and the evens together before subtracting them to find the final result. For example: (1 + 3 + 5 + 7 + 9) - (2 + 4 + 6 + 8) = ...

What's the reason for the inability to resize fieldset using both?

Can someone explain why the resize control is not enabled on the fieldset element? The documentation mentions that resize does not work with: Inline elements Block elements that have overflow set to visible fieldset { resize: both; overflow: h ...

Encountering issues with property not being found when using connect() with React, Redux, and TypeScript

I'm struggling to correctly define the access of properties and methods on distinct components using the connect() functionality. Here's what I currently have in my redux-folder: /redux/app/hooks.ts import { TypedUseSelectorHook, useDispatch, us ...

Obtaining JSON data from an external URL

I need to extract certain information from a specific web page. There is a JSON service that displays the data I require, and I have the URL for it: My goal is to capture and retain the specific number shown on the page. While testing this example, ever ...

Customized pop-up alerts on web browsers

Is there a library available that provides notification features similar to those seen on Web Slack and Web Skype, allowing users to receive notifications even when they are not currently on the site page? https://i.sstatic.net/wANRg.png Thank you, and I ...

Why does the same error keep popping up every time I attempt to install my React application?

I am new to React and feeling frustrated as I keep encountering the same error repeatedly. I have tried three different codes individually: npx create-react-app myapp npm init react-app myapp npm install -g create-react-app followed by create-react- ...

Achieving Perfect Alignment: Centering First Row Content to Full Width and Second Row to a 50/50 Split Using Bootstrap and HTML

I am trying to achieve a layout using Bootstrap that resembles the following image: https://i.sstatic.net/mharU.jpg This is the code I have so far: <div class="container"> <div class="row"> <div class="c ...

Removing the displayed image chips from the database using reactjs

How can I remove an image chip displayed from the database? Here is the code for displaying images from the database: {user.isImageUploaded != null ? <div > <p> {user.isImageUploaded.map(item => { const datatypeV ...

What is the best way to set an object's value to null in AngularJS?

Check out this code snippet var data={}; data={stdId:"101"}; data={empId:"102"}; data={deptId:"201"}; In my project, I'm receiving data from services into a data object with differing key names such as stdId or empId, etc. I need to set empty val ...