I have a little doubt, I have a status like this
const [searchItems, setSearchItems] = useState({
videos: [],
texts: [],
audios: []
});
My idea is to push these arrays inside the object searchItems
, if it were pure javascript it would be something likeseachItems.videos.push(object)
but being a state with useState, I must make use of thesetSearchItems
Does anyone know how to do it ?
i have something like
setSearchItems({
videos: test_search.videos.filter(video =>
video.name.includes(search)
)
});
but it doesn't work well at all.
I managed to fix it, but now I have another problem. I have this code
useEffect(() => {
if (showVideos) {
setSearchItems({
...searchItems,
videos: test_search.videos.filter(video =>
video.name.includes(search)
)
});
}
if (showTexts) {
setSearchItems({
...searchItems,
texts: test_search.texts.filter(text =>
text.name.includes(search)
)
});
}
if (showAudios) {
setSearchItems({
...searchItems,
audios: test_search.audios.filter(audio =>
audio.name.includes(search)
)
});
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [search, showVideos, showTexts, showAudios]);
The problem is that it is only assigning the last one, in this case the audios, the others are left empty, how could I solve this?
Beforehand thank you very much.
When you make use of the setSearchItems function you have to pass the entire object, not just the video as in this case. What you can do is use the spread operator (...) to copy the object and replace the field of the object you want (videos in this case).
Example:
With this, what you do is copy the searchItems object and replace the value of videos with the one you indicate with that filter.
I hope it works for you. Greetings.
Suppose you were to search in a list of fruits:
code in your html:
------------search component code
What I suggest you do is use the spread operator , that is
...elementos
to be able to obtain the copy of the elements of the object and also make use of destructuring to decompose an object and thus facilitate its handling.Now, let's say you have a new element for your video array:
mivideo
and we need to push or insert it into our arrayvideos
.What we will do is the following:
Now, we proceed to add it :
Departure:
As you will notice, a new item has been added to our video array. Similarly, you can make a
push
to othersarrays
.