EzJS
EzJS

Reputation: 229

Get data from Axios request

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}/>

 ));

Upvotes: 0

Views: 84

Answers (1)

SuleymanSah
SuleymanSah

Reputation: 17898

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;

Upvotes: 1

Related Questions