Mapping data in reactJS involves using the `map()` function to iterate over

Whenever I try to use items.map, it returns an error saying items.map is not a function. I am working on my wishlist feature, retrieving data from localStorage, but I can't seem to perform the map operation successfully.

How do I iterate over this data in order to access x.id for example?

items?.map((x) => {console.log(x.id)})

The above code snippet doesn't seem to be functioning as intended.

import React, { useEffect, useState } from 'react';

const Wishlist = () => {
  useEffect(() => {
    const items = localStorage.getItem('liked');
    items?.map((x) => {
      console.log(x.id);
    });

    console.log('items', items);
  });

  return <div className="test">hello world</div>;
};

export default Wishlist;

The line console.log('items', items); does work. It displays

[{ my all data},{like this},{there everything good}]

Answer №1

When retrieving data from local storage, it is important to note that the data is typically in a string format and not an array. This means that you cannot use array methods directly on it.

To address this issue, you must first parse the data so that you can then iterate over it effectively.

Below is an example code snippet demonstrating how to parse the data:

const parsedData = JSON.parse(localStorage.getItem("liked"))

Answer №2

You need to properly extract and interpret the information retrieved from local storage

const storedItems = JSON.parse(localStorage.getItem('liked')); 

Additionally, make sure to include the return statement within the arrow function used in the map method:

storedItems?.map((item) => {
      console.log(item.id);
      return item.id;
    })

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

Sort information based on the initial letter

My challenge is to accurately filter data by the starting letter only, not including middle letters. For example, if I have the word "Karnataka" and want to filter by the letter "K", searching with middle letters like "rna" still filters the result. Howe ...

Upload an image to a Node.js API using the Next.js API directory

I am working with a file instance that I obtained from the formidable library. Here's how it looks: photo: File { _events: [Object: null prototype] {}, _eventsCount: 0, _maxListeners: undefined, size: 16648, path: 'public/ ...

Repeated item discovered post-Ajax execution

I am currently working on implementing auto-complete functionality for form fields using AJAX and jQuery. Initially, I utilized Django and the views.py function below: def CreateWellMon(request): if request.method == 'POST': form = Su ...

Proper method for executing a synchronous AJAX POST request and subsequently submitting a form

Currently, I have an ASP submit button in my code. <asp:button runat="server" Text="Submit" id="btnSubmitOrder" OnClientClick="return SubmitOrder()" /> The JavaScript function I'm using, SubmitOrder(), is designed to execute a POST request. De ...

Capturing data from button inputs and the timing intervals between presses

I am currently facing a challenging ajax/php issue: In my project, there are 4 buttons that, when pressed, log the press event to a text file using a string representation. This string is named foo1 For example, if I were to press the first button 3 tim ...

Attempting to assign a value to the Progress Circle

Can I modify the code to incorporate a hardcoded number instead of displaying "Goals completed:" and still have the progress bar reflect the percentage? I want to hide the prompt for users to input a number and handle all updates behind the scenes. Essent ...

Utilizing CSS Masks in Bootstrap 4

Is it possible to create a "Mask" effect in CSS without using Bootstrap 4 or 5? Adding a background color and z-index to an image doesn't seem to achieve the desired effect. Learn more about creating masks in CSS here. ...

What is the process for deleting headers in a $http.get call and simultaneously including "application/json" and "text/plain" under the "Accept" header?

I'm relatively new to angularjs and I'm currently working on implementing some new features to an existing Angular JS application. The current API calls are quite intricate so I decided to make a direct call. Below is the code snippet for my new ...

A specialized version of BeautifulSoup for C/CPP that excels in handling improperly formatted HTML

Can anyone suggest a c/cpp library that is ideal for parsing, iterating, and manipulating HTML streams/files, even if they may contain errors such as unclosed tags? BeautifulSoup ...

I'm sorry, there seems to be a JSON error. The syntax is incorrect and it

I am facing a problem where I encounter an error when trying to post a JSON object. The error message reads: SyntaxError: JSON.parse: unexpected character Here is my JavaScript object: var $arr_data = { title: '', category: &apo ...

Is there a way to conceal a video preview in HTML code?

Currently working on my very first website, and I ran into an issue. I have successfully created a button that starts a video when clicked, but I don't want the video preview to be visible until the button is pressed. Does anyone know how I can hide t ...

I have implemented a feature in my code where the camera rotates when clicked. However, the rotation currently jumps to a 90-degree angle instantaneously. How can I adjust this to create

I'm working on an app that allows me to rotate the camera in order to view a specific entity, but I'm encountering a problem where the rotation is too abrupt. How can I make it transition more smoothly? I attempted to attach an animation compone ...

I'm curious to know how this code is extracting parameters from the website URL. Can someone walk me through the process step by step?

I needed to extract parameters from a URL and started searching online for solutions. I came across a helpful link that provided the information I was looking for: After visiting the website, I found this code snippet: function getUrlVars() { var var ...

The tooltips in the WordPress-Gulp-Starter-Kit running on Bootstrap 5 do not seem to be functioning properly

I'm having trouble with tooltips not working properly. The codebase I'm using is from this repository https://github.com/oguilleux/webpack-gulp-wordpress-starter-theme If you need more details, feel free to reach out. Here is my main.js file: ...

Apply a tint to the specified section

I'm looking to add a semi-transparent color overlay to my HTML section, but I'm facing an issue where it doesn't cover the entire section. Here's what I have so far: #main { padding-top: 50px; padding-bottom: 50px; backgr ...

Attempting to implement bootstrap-select to enhance my dropdown menu

Currently, I am in the process of developing a website using Bootstrap and have encountered an issue with a select component. Below is the code snippet: <tr> <td> <div class="textAlignCenter"> <select cl ...

Tips for finding the most efficient route from a specific point on a 2D plane using an array of location objects

I am working with an array that contains objects representing various locations, and I am trying to find the closest point to a specific starting point. //location array let locations=[ { x_axis:900, y_axis:900, }, { x_axis:800, y_axis:800, }, { x_ax ...

Guide on how to display matching options in an input box using HTML datalist based on user input at the beginning

I am a beginner in React and I am looking to create an autocomplete suggestion box for a text input field. I want the suggestions to only match the first letters of the available options, unlike the current behavior of HTML's <datalist>. Althou ...

Navigating through different components using React router version 4 and accessing inner

Transitioning from my background in Angular, I am attempting to recreate familiar functionalities using Angular's ui-router. My goal is to establish a main template for the application that features a static sidebar and dynamically changing views bas ...

Cannot locate module using absolute paths in React Native with Typescript

I recently initiated a new project and am currently in the process of setting up an absolute path by referencing this informative article: https://medium.com/geekculture/making-life-easier-with-... Despite closely following the steps outlined, I'm en ...