Search code examples
reactjsreduxreact-reduxconditional-rendering

How to show the message when there are no posts in user feed in react redux?


Right now, if I go to my feed where the lists of posts is shown. So, when there is no post made, I want to show No posts found message. I'm getting isFetching and posts through mapStateToProps.

posts is an array field in the reducer, and it's intial state is empty. So, when no posts are made, the array is empty.

How do I show the message though?

  render() {
    const { isFetching, posts  } = this.props

    return isFetching ? (
      <p>Fetching....</p>
    ) : (
      <div>
        {posts &&
          posts.map((post) => {
            return <Cards key={post._id} post={post} />
          })}
      </div>
    )
    ```

Solution

  • The same way you're checking isFetching, but instead use posts.length != 0.

    return isFetching ? (
        <p>Fetching....</p>
    ) : (
        <div>
            {(posts && posts.length != 0) ?
                posts.map((post) => { 
                    return <Cards key={post._id} post={post} />
                }) : <p>No posts found</p>}
        </div> 
    )