0

I currently have a component that holds a posts array, this component takes in a prop called sortBy which tells the component to either fetch data sorted by popular or new. The way my component is set up is upon initialization the posts are fetched then stored in redux, I only get new posts if my posts is empty. That way I'm not constantly fetching new data.

const posts = useSelector((state) => state.posts.posts);
useEffect(() => {
    const { sortby } = props;
                            // here I would like to check if props has changed
    if (Object.keys(posts).length === 0) {
      dispatch(getPostsAsync(sortby)).then((response) => {
        setLoading(false);
      });
    }
  }, [dispatch, props, posts]);

Now I would like to check if the sortBy props has changed value. So originally it might be sortby='-numLikes' but when I sortby 'new' it should then be sortby='-createdAt' after it changes I would like to tell Redux to fetch new data.

Dylan L.
  • 1,243
  • 2
  • 16
  • 35

1 Answers1

1

All you need to do to get the behavior you want is to change the useEffect to:

const posts = useSelector((state) => state.posts.posts);
const { sortby } = props;
useEffect(() => {
  dispatch(getPostsAsync(sortby)).then((response) => {
    setLoading(false);
  });
}, [dispatch, sortby]);

Then the useEffect will run every time sortby is changed.

Chad S.
  • 6,252
  • 15
  • 25
  • So i should just forget about the re-fetching of data? Right now Redux stores the data so when I change a page and come back it doesn't have to re-fetch, but I can just get rid of that I guess. – Dylan L. Apr 17 '22 at 22:54
  • 1
    They key here is destructuring `sortby` outside the useEffect - this way you use that value as the dependency to the hook instead of `props`. – Derek Apr 17 '22 at 23:00
  • If you want to avoid re-fetching you'll need to store the sort your results are using in the redux state along with the posts. i.e. `state = { posts, sortby }` and select the sortby via useSelect (rather than in props) then pass it as a dependency to the useEffect as above. – Chad S. Apr 18 '22 at 02:16
  • Or integrate react-query (or some other fetching state machine) to cache the results for you to avoid the re-fetch. – Chad S. Apr 18 '22 at 02:17