skip to Main Content

When I write items.map it gives me items.map is not a function. I am doing it for wishlist, taking data from localStorage, but I can’t map it.

how can i map this data for write x.id for example

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

is not working.

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;

console.log('items', items); is working. I can see [{ my all data},{like this},{there everything good}]

2

Answers


  1. The Returned data from local storage is mostly string (or whatever it is, it’s not an array) so logically that you cannot use array methods (not just map)

    So to solve this problem you need to parse the data and by this, you can iterate over it.

    a code that demonstrates how to parse it

    const parsedData = JSON.parse(localStorage.getItem("liked"))
    
    Login or Signup to reply.
  2. You have to parse the data that you are getting from local storage

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

    and then, in the arrow function inside the map method, you are missing return the value

    items?.map((x) => {
          console.log(x.id);
          return (x.id)
        })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search