Roni
Roni

Reputation: 25

How to update an array stored in the localStorage using hooks?

So I have a component which when clicked must store the ID of a city in an array in localStorage. I am using a custom hook for this as mentioned below. The problem I am facing is whenever the component gets clicked it completely rewrites the value in the localStorage instead of pushing the new value.

import React, {useEffect, useState} from  'react';
import styled from 'styled-components';

const Container = styled.div`
   background-color: white;
   display: flex;
   position: relative;
   flex-direction: column;
   align-items: center;
   justify-content: center;
   width: 100%;
   cursor: pointer;
   padding: 2rem;
   margin-top: 2rem;
   transition: all 0.2s ease;
   border-radius: 5px;
   box-shadow: 0 .1rem 1rem 5px rgba(0,0,0,0.07);
   &:hover{
     box-shadow: 0 .1rem 1rem 5px rgba(0,0,0,0.16);
     transform: translateY(-3px);
   }
`;
  const SearchedCity = (props) => {
  const [storedId, setId] = useLocalStorage('ids', []); 

  let handleId = () => {
     setId(prev => [...prev, props.cityId]);
  }

  return (
     <Container onClick={handleId}>
         {props.children}
     </Container>
  )
 }


 const useLocalStorage = (key, initialValue) => {
   const [storedId, setStoredValue] = useState(() => {
     try {
       const item = window.localStorage.getItem(key);
       return item ? JSON.parse(item) : initialValue;
     } catch (err) {
       console.error(err);
       return initialValue;
     }
   });

   const setValue = value => {
     try {
       const valueToStore =
       value instanceof Function ? value(storedId) : value;
       setStoredValue(valueToStore);
       window.localStorage.setItem(key, JSON.stringify(valueToStore));
     } catch (err) {
       console.error(err);
     }
   };

   return [storedId, setValue];
 };

 export default SearchedCity;

Upvotes: 0

Views: 1112

Answers (1)

Sergej Klackovskis
Sergej Klackovskis

Reputation: 453

Before updating localStorage value you can do something like:

  1. Get localStorageValue. In your case it should contain stringified array.
  2. Parse it.
  3. Add your new value to the parsed array.
  4. Stringify an array and update your local storage.
const array = localStorage.get(yourKeyHere);
const parsedArray = array ? JSON.parse(array) : [];
const newArray = [...parsedArray, newItem];
localStorage.set(yourKeyHere, JSON.stringify(newArray));

Upvotes: 1

Related Questions