user15134931
user15134931

Reputation:

How to map this given api response in react js javascript

I am getting an error when i was calling an post request in use effect hook and i got the response as promise pending, but the object is there, please see the response and please provide a perfect code to map this response.

enter image description here

code

function Comment({ id }) {
    const [data, setdata] = useState([]);
    console.log(id);
    useEffect(() => {
        const query = `
    query{
      forumAnswerId(id:${id}){
        forumAnswerBody
        forumAnswerTime
        forumAnswerCode1
        forumAnswerCode2
        forumAnswerCode3
        forumAnswerAuthor
        forumAnswerBoolean
        forumAnswerCode1Title
        forumAnswerCode2Title
        forumAnswerCode3Title
      }
      forumComment(forumAnswerComment:${id}){
        forumAnswerCommentPost
        forumAnswerCommentBody
        forumAnswerCommentAuthor
        forumAnswerCommentTime
        
      }
    }
  `;

        const opts = {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ query }),
        };
        const res = fetch('http://127.0.0.1:8000', opts).then((res) => res.json());

        setdata(res);
    }, []);
    return <div></div>;
}

export default Comment;

Upvotes: 0

Views: 471

Answers (3)

Rajdeep D
Rajdeep D

Reputation: 3920

useEffect(() => {
    const fetchData = async () => {
const query = `
query{
  forumAnswerId(id:${id}){
    forumAnswerBody
    forumAnswerTime
    forumAnswerCode1
    forumAnswerCode2
    forumAnswerCode3
    forumAnswerAuthor
    forumAnswerBoolean
    forumAnswerCode1Title
    forumAnswerCode2Title
    forumAnswerCode3Title
  }
  forumComment(forumAnswerComment:${id}){
    forumAnswerCommentPost
    forumAnswerCommentBody
    forumAnswerCommentAuthor
    forumAnswerCommentTime
    
  }
};`

const opts = {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ query }),
    };
    const res = await fetch('http://127.0.0.1:8000', opts).then((res) => res.json());

    setdata(res);
}

fetchData();

}, []);

Upvotes: 0

Nithin K Joy
Nithin K Joy

Reputation: 963

promise result cannot be accessed outside. You need to set data inside the then function

Using Promise

fetch('http://127.0.0.1:8000', opts).then((res) => setdata(res.json()));

Using Async await

const res=await fetch('http://127.0.0.1:8000', opts)
setdata(res.json())

Upvotes: 0

tuan nguyen
tuan nguyen

Reputation: 386

here you are:

fetch('http://127.0.0.1:8000', opts)
    .then((res) => res.json())
    .then(r=> setdata(r))

Upvotes: 2

Related Questions