Home > Software design >  can any array of string can be stored on localStorage?
can any array of string can be stored on localStorage?

Time:08-31

I want to store an array of addresses in the localstorage, e.g

addresses["1 doe st, england","2 doe st, england", "3 doe st, england"]

I want every time I click on a string it to push to the array of addresses in the localStorage, I have got this implementation but can only push the first click

  const AddRToLocalStorage = (addressText: string): void => {
    if (!localStorage.getItem('addresses')) {
      localStorage.setItem('addresses', JSON.stringify(addressText))
    }
  }

.....
   {requestedAddress.map((address, index) => {
                const addressText = `${query}, ${address.line_1}, ${address.district}, ${address.town_or_city}`
                return (
                  <p
                    onClick={() => AddRToLocalStorage(addressText)}
                    key={index}
                  >
                    {addressText}
                  </p>
                )
              })}

note that I don't want to have a separate key every time I click on an address to push to the localstorage so basically I don't want this result enter image description here

I want this resultenter image description here

CodePudding user response:

You should be using a state to store your addresses, and everytime it updates you can update your localStorage with a useEffect() hook

const [addresses, setAddresses] = useState([]);

useEffect( () => {
    if (!localStorage.getItem('addresses')) {
      localStorage.setItem('addresses', JSON.stringify(addresses))
    }
}, [addresses]);

const AddRToLocalStorage = (addressText: string): void => {
    setAddresses([...addresses, addressText]);
}

...

CodePudding user response:

You should append your selection to the array if address key is already set in localstorage

const AddRToLocalStorage = (addressText: string): void => {
    if (!localStorage.getItem('addresses')) {
      localStorage.setItem('addresses', JSON.stringify([addressText]));
    } else{
        const addressList = JSON.parse(localStorage.getItem('addresses'));
        addressList.push(addressText);
        localStorage.setItem('addresses', JSON.stringify(addressList));
    }
}
  • Related