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

71
Vistas
How to make a JSON response data global :)

Currently working on a stock project for my portfolio and I am using finnhub as the API. I can log everything to my console. However I cannot render it as the "data" is not globally declared and must be inside of a certain function.

I tried rendering globally but had no luck...

So my question is how do I make 'data' global so that I can render it inside of the "StockHeader's" return ?

Heres what I have so far...

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


const StockHeader  = (data) => {

  const [stocks, setStocks] = useState({});
  const getStocks = () => {
    //setting stocks
    setStocks(stocks)

}

//calling it once
useEffect(()=> {

  getStocks();

}, [])


//using finhubs ready made code from documentation

const finnhub = require('finnhub');
const api_key = finnhub.ApiClient.instance.authentications['api_key'];
api_key.apiKey = "my apikey" 
const finnhubClient = new finnhub.DefaultApi()

finnhubClient.quote("AAPL", (error, data, response) => {

  //I can log the data but I cant show it in my component
 console.log(data.c)

});

return (
  <>
  {/* This says that data is not defined */}
    <h1>{data.c}</h1>
  </>
)


}


export default StockHeader 

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

0

You just need a little bit of code reorganization so that the API request only happens once and so that you can use setStocks to store it:

const StockHeader  = (data) => {

  const [stocks, setStocks] = useState({});

  useEffect(()=> {
    //this could be separated into a `getStocks` function if you want
    const finnhub = require('finnhub');
    const api_key = finnhub.ApiClient.instance.authentications['api_key'];
    api_key.apiKey = "my apikey" 
    const finnhubClient = new finnhub.DefaultApi()

    finnhubClient.quote("AAPL", (error, data, response) => {
      console.log(data.c);
      setStocks(data.c);
    });

  }, []);

  return (
    <>
      {/* You probably don't want to render `stocks` itself, but this shows you how to get access to the variable */}
      <h1>{stocks}</h1>
    </>
  )
}
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