A
A
angelzzz2020-04-18 16:01:59
React
angelzzz, 2020-04-18 16:01:59

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: []
  })


I make a request to the backend so that posts appear in Redux and when they appear (2) I fill the state of the component with these posts
useEffect(() => {
    dispatch(showPosts())

    setState(state => ({ ...state, postsFiltered: posts })); ///(2)
  }, [dispatch]); (3)


Next I make a list:
return (
       state.postsFiltered.map(post => {
              return (
                     {post.name}
              )
       })
)


The problem is that posts from Redux do not get into the state, I see that the Redux store is updated three times (two more actions are called on the pages).

Also, React insistently suggests adding posts to the array of the second argument to useEffect (3), and when I add it, it starts updating indefinitely.

How can I correctly transfer data from the redax to the state of the component?

UPD: probably for pro forma, you need to add a search function

const onSearch = (e) => {
    const postsFiltered = posts.filter(item => item.name.toLowerCase().includes(e.target.value.toLowerCase()))
    setState(state => ({ ...state, postsFiltered }))
  }


The text is changed on the fly by onChange:
<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 question

Ask a Question

731 491 924 answers to any question