Tengo una matriz en el almacenamiento local y estoy mapeando la matriz para representar sus datos en la lista. Quiero agregar un botón al lado de cada elemento en la lista y si hago clic en el botón, el elemento específico se elimina de la matriz en el almacenamiento local.
¿Es esto posible y cómo puedo hacerlo?
Usando -> código Javascript y React aquí:
//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> ); }Agregue algunos reptiles en el localStorage:
// in the Browser Console localStorage.setItem( "reptiles", ["alligator", "snake", "lizard"] )O agregue algunas otras funcionalidades para agregar reptiles desde la interfaz de usuario.
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> ); }Puede usar estas 2 funciones para obtener y eliminar elementos del almacenamiento local.
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)); }; Ahora, cuando esté representando la lista, represente un botón con cada elemento de la lista y llame a la función removeElementLocalStorage cuando se haga clic en el botón con el valor.
<li> <span>{reptile}</span> <button onClick={() =>removeElementLocalStorage(element.name)}>Remove</button> </li>