简体   繁体   中英

Delete specific element in the array in localstorage using javascript and React

I have an array in localstorage and I am maping the array to render it's data into list. I want to add button next to every element in the list and if I click the button the specific element gets deleted from the array in the localstorage.

Is this possible and how can I do it?

Using -> Javascript and React code here:


//This array is in the localstorage
const reptiles = ["alligator", "snake", "lizard"];

function ReptileList() {

  return (
    <ol>
      {reptiles.map((reptile) => (
        <li>{reptile} /*THERE SHOULD BE THE DELETE BUTTON*/</li>
      ))}
    </ol>
  );
}

You can use these 2 functions to Get and Remove Items from Local Storage.

const getElementsfromLocalStorage = () => {
    let elements = [];
    if (localStorage.getItem('reptiles')) {
        elements = JSON.parse(localStorage.getItem('reptiles'));
    }
    return elements;
};

const removeElementLocalStorage = (name) => {
    let elements = getElementsfromLocalStorage();
    elements = elements.filter(element => element.name !== name);
    localStorage.setItem('reptiles', JSON.stringify(elements));
};

Now, when you are rendering the list, render a button with every list item and call the function removeElementLocalStorage when the button is clicked with the value.

<li>
    <span>{reptile}</span>
    <button onClick={() =>removeElementLocalStorage(element.name)}>Remove</button>
</li>

Add some reptiles in the localStorage:

// in the Browser Console
localStorage.setItem( "reptiles", ["alligator", "snake", "lizard"] )

Or add some other functionalities to Add reptiles from the UI.

import "./styles.css";
import { useEffect, useState } from 'react';


export default function ReptileList() {

  const [ reptiles, setReptiles ] = useState( [] )

  function deleteReptile( name ){
    // Fin the index of the reptile
    let index = reptiles.indexOf( name )
    // if reptile is found
    if( index !== -1 ){
      // remove it from state
      reptiles.splice(index, 1 )
      // update localStorage
      localStorage.setItem( 'reptiles', reptiles )
      // update reptiles State to re-render the list
      setReptiles( [...reptiles] )
    }
  }

  function readReptiles(){
    // read from localStorage
    let reptiles = localStorage.getItem( 'reptiles' )
    
    // if no reptiles in localStorage initialize with empty
    if( reptiles === null ){
      reptiles =  []
    }
    // init reptiles State
    setReptiles( reptiles.split(',') )
  }

  useEffect(() => {
    // read reptiles from local storage after rendered
    readReptiles();
    return () => {};
  }, []);

  return (
    <div className="App">
      <h1>Reptiles</h1>
      {reptiles.map( (reptile => (
        <li key={reptile} >{reptile} - 
          <button onClick={()=>deleteReptile(reptile)}>Delete</button> 
        </li>
      )))}
    </div>
  );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM