Search code examples
javascripthtmlcssreactjsapi

How to map data in reactJS?


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}]


Solution

  • 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"))