-1

I try to build an app in React with Redux and i try to get data from my Redux store and send the data to my localStorage but I have a little problem because my data in localStorage is saved like:

data    [object Object],[object Object],[object Object],[object Object]

enter image description here

This is how i get and send data to my localStorage:

import React from 'react'
import { useSelector } from 'react-redux';

function Table() {
    const myUsers = useSelector((state) => state.users.data);

    function test() {
        let data = [];

        for (let i = 0; i < myUsers.length; i++) {
            data.push(myUsers[i]);
        }

        localStorage.setItem('data', data);
    }

    test();


    return (
        <div>Table</div>
    )
}

export default Table

My database:

const database = [
    {
        id: 1,
        email: "email1@gmail.com",
        birthYear: "1999",
    },
    {
        id: 2,
        email: "email2@gmail.com",
        birthYear: "1987",
    },
    {
        id: 3,
        email: "email3@gmail.com",
        birthYear: "2005",
    },
    {
        id: 4,
        email: "email4@gmail.com",
        birthYear: "1967",
    },
];
SnNaCk
  • 2,370
  • 2
  • 5
  • 16

2 Answers2

3

Try this

localStorage.setItem('data', JSON.stringify(data));
Inder
  • 1,711
  • 1
  • 3
  • 9
  • When you load the data from localstorage, you'll have to run JSON.parse – Inder Apr 28 '22 at 10:22
  • Thank you very much. I will upvote it in 15 mins when I will can – SnNaCk Apr 28 '22 at 10:23
  • 2
    This is an ***often*** repeated duplicate of https://stackoverflow.com/questions/2010892/how-to-store-objects-in-html5-localstorage. There's no need to have yet another copy of those answers here. – T.J. Crowder Apr 28 '22 at 10:26
-1

localstorage doesnt allow objects but only strings to be stored in them. so convert your array into string by JSON.stringify() and then store it using localStorage.setItem() or localStorage.getItem() an while getting the array use JSON.parse() To Set

localStorage.setItem('data', JSON.stringify(data))

To Get

JSON.parse(localStorage.getItem('data))
mrtechtroid
  • 658
  • 3
  • 14
  • 3
    This is an ***often*** repeated duplicate of https://stackoverflow.com/questions/2010892/how-to-store-objects-in-html5-localstorage. There's no need to have yet another copy of those answers here. – T.J. Crowder Apr 28 '22 at 10:26