0

While practicing React I wanted to take it further by showing complete post only if the post id == 2. I wanted to do with substring but didn't work, then I added toString() but still not working.

  <p> {postId == 2 ? post.body : post.body.toString().substring(2, 3)  } </p>

Here is a complete example, just uncomment the commented line https://codesandbox.io/s/useeffect-practice-fetch-gskpf?file=/src/index.js

3
  • Can you provide a sample JSON structure you are using. Commented Jun 25, 2020 at 11:44
  • * Are you sure post.body isn't empty (null, undefined, "", ...). Try console.log(post.body). * Are you sure postId is different from 2? Commented Jun 25, 2020 at 11:46
  • Here is a complete example, just uncomment the line to see the problem codesandbox.io/s/useeffect-practice-fetch-gskpf?file=/src/… Commented Jun 25, 2020 at 11:53

2 Answers 2

1

Before getting data from fetchPost and call setPost your post is empty object ==> post.body is undefined. Add question mark to check if it existing do the work

// add question mark after post and body
<p> {postId == 2 ? post.body : post?.body?.toString().substring(2, 3)  } </p>

Normal version

<p> {postId == 2 ? post.body : post.body ? post?.body?.toString().substring(2, 3) : 'loading...'  } </p>

Check the codesandbox for demo

Sign up to request clarification or add additional context in comments.

Comments

0

Try this one.... Hope it helps!!!!

let someword = "Hello there!";
console.log(someword.substring(0, 4));

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.