0

I have a parent component (App.tsx). In this component I'm defining a hook that holds and sets an array of numbers:

const [valuesList, setValuesList] = useState<number[]>([]);

for a previous childcomponent (AddNumber.tsx) I defined a function that adds a number to the array of numbers:

const addNumberToList = (num: number) => {
    setValuesList((prev) => prev.concat(num));
  };

then I passed the function to the child component. That worked fine.

However now I need to create a function to delete a number from the array.

Does anyone now how to implement that function?

In a previous app I implemented deleting a number from the list like this:

setValuesList(valuesList.filter((e) => e !== value));

But because I'm using TypeScript, I can't do it like that anymore, because I need to pass the deleteNumberFromList method to the childcomponent(NumberList.tsx)

Thanks for your help,

Anthony

Toontje
  • 1,197
  • 4
  • 18
  • 37
  • Does this answer your question? [Delete item from state array in react](https://stackoverflow.com/questions/36326612/delete-item-from-state-array-in-react) – Emile Bergeron Jul 16 '20 at 17:01

2 Answers2

1

It will be pretty similar, create a new function that takes the number as argument and updates the state after removing the number from the valuesList.

const removeNumberFromList = (num: number) => {
  setValuesList((prev) => prev.filter(el => el !== num))
}

// can be called like removeNumberFromList(10)
// or can be passed as onClick={() => removeNumberFromList(10)}

The type definition is pretty much the same

interface AppProps {
  addNumberToList: (num: number) => void;
  removeNumberFromList: (num: number) => void;
}
subashMahapatra
  • 3,537
  • 1
  • 6
  • 16
  • 1
    thanks @subashMahapatra, that worked! I tried something similar, but forgot to adjust the interface. – Toontje Jul 16 '20 at 16:56
0

You can still use that filter bit of code, you just have to add types to it:

    setValuesList((prev) => prev.filter((e:number) => e !== value));
Luke Storry
  • 3,868
  • 1
  • 2
  • 16