Dylan L.
Dylan L.

Reputation: 1317

Is there a way of running an if statement on whether or not props have changed in React

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.

Upvotes: 0

Views: 36

Answers (1)

Chad S.
Chad S.

Reputation: 6633

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.

Upvotes: 1

Related Questions