0

Ive tried several forum solutions but still stumped. Thanks for any help...

I am trying to display the number of total posts made by user by taking the most recent post's postCount.

My problem is when user hasn't posted anything yet and this.props.user.myFeed[0].postCount, the redux prop that holds user's posts/feed, hasn't been created yet. The screen tries to load and I get "TypeError: undefined is not an object (evaluating 'this.props.user.myFeed[0]')"

Ive tried several solutions but is there a reason why the simple code below doesn't work.

<Text>Posts: {(this.props.user.myFeed[0]) ? this.props.user.myFeed[0].postCount : 0 }</Text>

Also have tried below:

<Text>Posts: {(this.props.user.myFeed[0] === undefined) ? this.props.user.myFeed[0].postCount : 0 }</Text>

If the store is undefined, shouldn't it simply be 0 ?

Thanks again! -Matt

2
  • If the store is undefined, then it'll be just that… undefined. You can probably initialise the store to have some empty state so that you don't get the error, or check if this.props.user is defined before trying to access child keys. Commented May 1, 2020 at 0:04
  • By the way, myFeed is created as an empty array [] when the user is first created. In response to you, I thought thats what I was doing with the code above, checking to see if there is a most recent post myFeed[0] and then if it is undefined return 0; but if it is there, return its postCount prop. Didn't I write it correctly to perform that check and see if its undefined? Thanks again Commented May 1, 2020 at 0:12

1 Answer 1

1

As your myFeed is an empty array, which means myFeed[0] is returning error. Therefore you should check the myFeed is not undefined to proceed. Also check postCount if possible.

    <Text>Posts: {(this.props.user.myFeed && this.props.user.myFeed[0]) ?
 this.props.user.myFeed[0].postCount : 0 }</Text>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.