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]
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",
},
];
Try this
localStorage.setItem('data', JSON.stringify(data));
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))