Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why I cannot remove the element of the array of useState hook

This is the code,

import "./styles.css";
import Ank from "./Ank";
import { useState, useRef, useEffect } from "react";
export default function App() {
  const [array, setArray] = useState(
    JSON.parse(localStorage.getItem("notes")) ?? []
  );
  useEffect(() => {
    localStorage.setItem("notes", JSON.stringify(array));
  }, [array]);
  const Add = () => {
    setArray((e) => {
      return [...e, one.current.value];
    });
  };
  const deleting = (e) => {
    setArray((e1) => {
      return e1.filter((e2, index) => {
        return index !== e - 1;
      });
    });
  };
  const one = useRef(null);
  return (
    <>
      <div className="App">
        <h1>Hello CodeSandbox</h1>
        <div className="align">
          <input ref={one} />
          <br />
          <br />
          <button onClick={Add}>Add</button>
        </div>
        <div className="align">
          {array.map((e, index) => {
            return (
              <Ank key={index} onSelect={deleting} index={index + 1} name={e} />
            );
          })}
        </div>
      </div>
    </>
  );
}

Please check the function deleting in the filter section I am trying to delete the elemt from the array using setarray.

This is the codesandbox link

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

https://codesandbox.io/s/silly-neumann-b0foos?file=/src/App.js:0-1072

>Solution :

e is an object having index as prop… so its e.index

const deleting = (e) => {
  setArray((e1) => {
    return e1.filter((e2, index) => {
      return index !== e.index - 1; // here
    });
  });
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading