0

I have an api that returns the following data

[{…}] 0: {id: 1, postId: 86, commentBody: "This is a test comment", giphyUrl: "https://media2.giphy.com/", postPicture: "pic.com", …} length: 1 __proto__: Array(0) [{"id":1,"postId":86,"commentBody":"This is a test comment","giphyUrl":"https://media2.giphy.com/","postPicture":"pic.com","userId":1,"userIdto":2,"userIdName":"Elton","userIdtoName":null}] 

I want to access the comment body but when i do something like data.commentbody or data[0].commentbody i dont get the value back it returns undefined. please help, below is my axios request.

 const fetchComments = async (id) => { try { return await axios.get('http://10.6.254.22:5000/comments/' + id) } catch (error) { console.error(error) } } const comments = async(id) => { const fetchedComments = await fetchComments(id); console.log(fetchedComments.data) // console.log(fetchedComments.data.message) return fetchedComments.data } 

And then i want to send it as a prop to my react component

const reversedProps = this.props.posts.reverse(); const postItems = reversedProps.map(post => ( console.log('post id is===' + post.id), comments(post.id), <PostBodyTemplate key={post.id} title={post.title} postBody={post.postBody} giphyUrl = {post.giphyUrl} userWhoPosted={post.userIdName}/> )); 
4
  • 2
    Can you paste your data from api as json? Commented Oct 15, 2019 at 14:39
  • [{"id":1,"postId":86,"commentBody":"This is a test comment","giphyUrl":"media2.giphy.com/…}] Commented Oct 15, 2019 at 14:45
  • Please add the data in question by editing Commented Oct 15, 2019 at 14:46
  • I did its under original json data Commented Oct 15, 2019 at 14:47

1 Answer 1

1

You need to send your data to your component like this:

comments.map(comment => { return <PostBodyTemplate key={post.id} comment={comment} />; }); 

A more complete example:

import React, { useState, useEffect } from "react"; function App() { const [comments, setComments] = useState([]); useEffect(() => { const getComments = async () => { const response = await axios.get("http://10.6.254.22:5000/comments/1"); setComments(response.data); }; getComments(); }, []); return ( <div> {comments.map(comment => { console.log(comment.commentBody); // => you can access the commentBody like this return <PostBodyTemplate key={post.id} comment={comment} />; })} </div> ); } export default App; 
Sign up to request clarification or add additional context in comments.

2 Comments

I know how to pass the prop, the issue i am having is just getting the value of commentBody. How do i get just "This is a Test Comment". Once i get that i can pass it down as prop to get the comment displayed.
@EzJS you can access your commentBody inside the map like comment.commentBody

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.