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

1

2 Answers 2

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

thanks @subashMahapatra, that worked! I tried something similar, but forgot to adjust the interface.
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));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.