Home > Mobile >  Is there a way to put an array of objects in localstorage for the user then iterate through it in re
Is there a way to put an array of objects in localstorage for the user then iterate through it in re

Time:02-22

Basically I've been making a web app and been trying to figure out a way to be able to move the data from an api on a dropdown list and make it where when the user clicks on the item they want to "save" to the localstorage, but for some reason when you click on it the first time it doesn't register and you have to click on it a second time and then I tried to get it to save in localstorage and it just gives me [object Object]


    const [count, setCount] = useState(0);
    const [products, setProducts] = useState([]);
    const [product, setProduct] = useState([]);


    const setProductData = (data, i) => {

        setCount(count   1);
        let product = {
            id: data.id,
            product_number: data.product_number
        }
        setProduct([...product, { data }]);
        localStorage.setItem(`Product${i   1}`, [product.id, product.product_number])
        console.log(data);
    }


    const fetchProducts = async () => {
        await Axios.get(`${process.env.REACT_APP_API}/products`, {
            withCredentials: true
        })
            .then(res => {
                let data = res.data;
                setProducts(data.data);
            }).catch(error => {
                console.error('Error:', error);
            });
    }

    useEffect(() => {
        fetchProducts();
    }, [count]);

    return (
        <div>
            <h1>Select products</h1>
            <div className="mt-5 mb-5">
                <InputGroup>
                    <DropdownButton
                        variant="outline-secondary"
                        title={'Products'}
                        id="dropdown"
                    >
                        {
                            products.map((obj, i) => {
                                let product = obj.product_number;
                                return (
                                    <Dropdown.Item
                                        key={i}
                                        onClick={() => setProductData(obj, i)}>{product}</Dropdown.Item>
                                )
                            })
                        }
                    </DropdownButton>
                </InputGroup>
             </div>
           </div>
)

I've tried multiple ways to make the localStorage.setItem() to try and get the whole object but either shows as [object Object] or only part of what I am needing

and with the project object in the setProductData function, I already tried using the data argument and that just gives the [object Object]

CodePudding user response:

General issue is that localStorage stores data as string so to make it work you have to serialise data on storing and unserialise them on read

So for such case JSON.stringify on storing and JSON.parse on read

Imo you should serialize and store whole products object

CodePudding user response:

You can use localDataStorage to transparently store JavaScript data types (Array, Boolean, Date, Float, Integer, String and Object). It also provides lightweight data obfuscation, automatically compresses strings, facilitates query by key (name) as well as query by (key) value, and helps to enforce segmented shared storage within the same domain by prefixing keys. Additionally, it dispatches a custom event allowing you to respond to localStorage change events on the same page/tab that originated them.

[DISCLAIMER] I am the author of the utility [/DISCLAIMER]

Examples:

localDataStorage.set( 'key1', 'Belgian Chonklit' )
localDataStorage.set( 'key2', 1200.0047 )
localDataStorage.set( 'key3', true )
localDataStorage.set( 'key4', { 'RSK' : [1,'3',5,'7',9] } )
localDataStorage.set( 'key5', null )

localDataStorage.get( 'key1' )   -->   'Belgian Chonklit'
localDataStorage.get( 'key2' )   -->   1200.0047
localDataStorage.get( 'key3' )   -->   true
localDataStorage.get( 'key4' )   -->   Object {RSK: Array(5)}
localDataStorage.get( 'key5' )   -->   null

As you can see, primitive values are respected, including objects. Use it in Angular, ReactJS or Vanilla JavaScript.

CodePudding user response:

    localStorage.setItem(`Product${i   1}`, JSON.stringify([product.id, product.product_number]))

//while fetching you need to parse 

JSON.parse(localStorage.getItem(Product${i   1}))
  • Related