krishna kakade
krishna kakade

Reputation: 479

Fetching data in React's useEffect() returns data “undefined”

I am trying to fetch data in reactjs with help of use effect hook but after accessing that in return div it is showing data undefined code is given below for that

import React,{ useEffect } from 'react'

export default function Home() {
useEffect(() => {
    fetch("https://lighthouse-dot-webdotdevsite.appspot.com//lh/newaudit", {
      method: "POST",
      body: JSON.stringify({
      "url": "https://piyushsthr.netlify.app",
      "replace": true,
      "save": false
    }),
      headers: {
        "Content-Type": "application/json; charset=utf-8"
      },
      credentials: "same-origin"
    })
     .then(res => res.json()) // this is the line you need
     .then(function(data) {
  
  
      console.log(data.lhrSlim[0].score)
      //return data;
  
    }).catch(function(error) {
      // eslint-disable-next-line no-unused-expressions
      error.message
    })
  }, )
  return (
    <div>
      <h1>{data.lhrSlim[0].score}</h1>
    </div>
  )
}

can anyone help me to fix this thing

Upvotes: 1

Views: 930

Answers (2)

Junius L
Junius L

Reputation: 16132

To display the data from the api add a state in your component.

const [score, setScore] = useState([]);

then set score

 .then(function (data) {
    setScore(data?.lhrSlim[0]?.score);
  })

https://codesandbox.io/s/proud-surf-v9gjb?file=/src/App.js

Upvotes: 1

Alejandro Vicaria
Alejandro Vicaria

Reputation: 158

You cannot directly show the content of the request directly on the UI, to do that either it has to be a prop or be stored in the state, for example you could do this.

import React, { useEffect, useState } from 'react'

export default function Home() {
const [State, setState] = useState("");

useEffect(() => {
    fetch("https://lighthouse-dot-webdotdevsite.appspot.com//lh/newaudit", {
      method: "POST",
      body: JSON.stringify({
      "url": "https://piyushsthr.netlify.app",
      "replace": true,
      "save": false
    }),
      headers: {
        "Content-Type": "application/json; charset=utf-8"
      },
      credentials: "same-origin"
    })
     .then(res => res.json()) // this is the line you need
     .then(function(data) {
  
      setState(data.lhrSlim[0].score);

    }).catch(function(error) {
      // eslint-disable-next-line no-unused-expressions
      error.message
    })
  }, )
  return (
    <div>
      <h1>{State}</h1>
    </div>
  )
}

That way you will be able to store the data from the response directly on the state of the component and be able to show it afterwards.

Upvotes: 1

Related Questions