Home > OS >  How to make a JSON response data global :)
How to make a JSON response data global :)

Time:11-08

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 

CodePudding user response:

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>
    </>
  )
}
  • Related