Answer the question
In order to leave comments, you need to log in
How to copy a Redux state to a component state with hooks?
I need to do a live search.
To do this, I get a list of posts from the Redux
store. I create a filtered list in the component's state.
const posts = useSelector(state => state.posts);
const [state, setState] = useState({
postsFiltered: []
})
useEffect(() => {
dispatch(showPosts())
setState(state => ({ ...state, postsFiltered: posts })); ///(2)
}, [dispatch]); (3)
return (
state.postsFiltered.map(post => {
return (
{post.name}
)
})
)
const onSearch = (e) => {
const postsFiltered = posts.filter(item => item.name.toLowerCase().includes(e.target.value.toLowerCase()))
setState(state => ({ ...state, postsFiltered }))
}
<Search
placeholder="input search text"
onChange={onSearch}
/>
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question