Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

200
Vistas
Accessing an object from a fetch request - javascript/react

I'm trying to access the response body of an API request to Bing News (in a React component). I know the response is successful and provides an object (image from log below), but when I try to access values in the object, the log says the "data is undefined". I've tried accessing them with data.value and data ["value"], but with the same result. JavaScript is not a language I write very often in, so sorry in advance if the answer is blindingly obvious: but how do I access the values in the object?

import { useEffect, useState } from "react";
import "./StockBlock.css";

function News() {
  const [data, setData] = useState();
  function fetchData() {
    fetch(
      "https://bing-news-search1.p.rapidapi.com/news?textFormat=Raw&mkt=en-WW&headlineCount=10&category=business",
      {
        method: "GET",
        headers: {
          "x-bingapis-sdk": "true",
          "x-rapidapi-host": "bing-news-search1.p.rapidapi.com",
          "x-rapidapi-key": "key",
        },
      }
    )
      .then((response) => {
        setData(response.json());
        data && console.log("data", data.values); <<<--Error comes here
      })
      .catch((err) => {
        console.error(err);
      });
  }
  useEffect(() => {
    const timer = setInterval(() => {
      fetchData();
    }, 3000);
    return () => clearInterval(timer);
  });

  return <div></div>;
}

export default News;

When I log the whole variable I get this response:

enter image description here

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

The issue is that response.json() returns a Promise, so you need to add another .then() to that.

However a better option, in my opinion, is to make your fetchData function an async function so you can use the await operator:


    import { useEffect, useState } from "react";
    import "./StockBlock.css";
    

    async function fetchData() {
        
        const url = "https://bing-news-search1.p.rapidapi.com/news?textFormat=Raw&mkt=en-WW&headlineCount=10&category=business";
        const opts = {
            headers: {
              "x-bingapis-sdk": "true",
              "x-rapidapi-host": "bing-news-search1.p.rapidapi.com",
              "x-rapidapi-key": "key",
            }
        };

        try {
            const resp = await fetch( url, opts );
            const data = await resp.json();
        
            console.log( "data: %o", data );
            setData( data );
        }
        catch( err ) {
            debugger;
            console.error( "fetch failed: %o", err );
        }
    }

    function News() {
        const [data, setData] = useState();

        useEffect( () => {
            const timer = setInterval( fetchData, 3000);
            return () => clearInterval( timer );
        } );
    
        return <div></div>;
    }
    
    export default News;

about 4 years ago · Juan Pablo Isaza Denunciar

0

This code should work

import { useEffect, useState } from "react";
import "./StockBlock.css";

function News() {
  const [data, setData] = useState();
  function fetchData() {
    fetch(
      "https://bing-news-search1.p.rapidapi.com/news?textFormat=Raw&mkt=en-WW&headlineCount=10&category=business",
      {
        method: "GET",
        headers: {
          "x-bingapis-sdk": "true",
          "x-rapidapi-host": "bing-news-search1.p.rapidapi.com",
          "x-rapidapi-key": "key",
        },
      }
    )
      .then((response) => {
        response.json().then((json) => {
          setData(json);
          data && console.log("data", data.values);
        })
      })
      .catch((err) => {
        console.error(err);
      });
  }
  useEffect(() => {
    const timer = setInterval(() => {
      fetchData();
    }, 3000);
    return () => clearInterval(timer);
  });

  return <div></div>;
}

export default News;

This works because response.json returns a Promise.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda