Search code examples
javascriptreactjsreduxlocal-storage

Can't send data to localStorage in React


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: "[email protected]",
        birthYear: "1999",
    },
    {
        id: 2,
        email: "[email protected]",
        birthYear: "1987",
    },
    {
        id: 3,
        email: "[email protected]",
        birthYear: "2005",
    },
    {
        id: 4,
        email: "[email protected]",
        birthYear: "1967",
    },
];

Solution

  • Try this

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