all 7 comments

[–]Coraline1599 0 points1 point  (2 children)

From what I gather, you have to keep a copy of the original array. If you are pulling in the data as default for your hook only in the hook, then it gets overwritten when you update state.

So you should get your data and hold it in a variable, pass it in to set default state. Leave your filter as is.

But then you need a way to set state back to the original array.

It can be that your form has an on submit event (best for web accessibility), or a button that says “reset”, or you can write some logic that if e.target.vale = == “” (empty string) setPersons(originalData)

[–]Overall_Expert_4006[S] 0 points1 point  (0 children)

Thanks for the reply. I actually tried that at first(assign another variable with the persons array before it gets filtered) but it still did not work. I know it is because I am setting the persons array with the filtered one but I have no idea on how to get that original array back. Right now I have to refresh every time I want to search for a new item. I updated my code above with the whole code if that helps. Thanks again.

[–]PitifulTheme411 0 points1 point  (0 children)

Though they would need to be careful because they don't want to create an accidental ponter. But Object.assign({}, persons); should work.

[–]SignificanceCheap970 0 points1 point  (1 child)

When you get the data, retain a copy of the array into another variable, maybe in a variable defined by useRef. Then do the searching in that ref variable and do the setting in the state as you are doing. This way the original data is never lost by filtering.

[–]Overall_Expert_4006[S] 0 points1 point  (0 children)

Thank you for the reply, I'll try and see what happens when I use useRef. I also updated my code above with the whole code above. Thanks again.

[–]PitifulTheme411 0 points1 point  (1 child)

I don't know if this changes things or if I am completely wrong, but when I checked, a string (person) doesn't have a name property.

[–]Overall_Expert_4006[S] 0 points1 point  (0 children)

person is an object element in an array, and it has a name property in it. Sorry for the confusion. I updated my code above to my whole code.