How can I share variable data across different files in React

Caleb

I am trying to set up graphs in my stockmarket project. I am trying to display the graph of the stock clicked on in Gatsby.

Currently, I can display the stock graph of any stock by manually typing in the stock name to the code. I would like to replace the stock name with ${query} inside of the url of the api call because of const query = event.target.value in index.js. So the searched term will be saved as query and I need to have access to the same variable in my other file chartData.js so that I can change my API call from let API_CALL = `https://cloud.iexapis.com/stable/stock/aapl/chart/5y?token=${API_KEY}`; into let API_CALL = `https://cloud.iexapis.com/stable/stock/${query}/chart/5y?token=${API_KEY}`; Thus I will have access to whichever term is searched and be able to turn it into a graph.

I thought maybe I could use state to do this, like moving query to state via query: this.state.value or query: {this.state.value}. Both of these returned errors so I figured that would not work (or I was doing it wrong at least).

index.js

import React from "react"
import { Link } from "gatsby"
import axios from "axios"
import "../css/style.css"
import Layout from "../components/layout"
import { symbol } from "prop-types"

export default class index extends React.Component {
  state = {
      companyName: "",
      previousClose: "",
      marketCap: "",
      change: "",
      symbol: "",
      topStocks: [],
      Yearweekhigh: "",
      Yearweeklow: "",
      avgTotalVolume: "",
      peRatio: "",
      

  }
     
  

  clickHandler = (event) => {
          if (event.keyCode === 13) {
          const query = event.target.value;
          const API_KEY = '******************';
      axios.get(`https://cloud.iexapis.com/stable/stock/${query}/quote?token=${API_KEY}`)
          .then(res => {
              const companyName = res.data['companyName'];
              this.setState({ companyName })

              const previousClose = res.data['previousClose'];
              this.setState({ previousClose })

              const marketCap = res.data['marketCap'];
              this.setState({ marketCap })

              const change = res.data['change'];
              this.setState({ change })

              const symbol = res.data['symbol'];
              this.setState({ symbol })

              const Yearweekhigh = res.data['week52High'];
              this.setState({ Yearweekhigh })

              const Yearweeklow = res.data['week52Low'];
              this.setState({ Yearweeklow })

              const avgTotalVolume = res.data['avgTotalVolume'];
              this.setState({ avgTotalVolume })

              const peRatio = res.data['peRatio'];
              this.setState({ peRatio }) 


          })
      }
  }



  render() {
      return (
          <Layout>
              <div class = "main-div">
                  <input type="search" class="main-search" onKeyDown={event => this.clickHandler(event)}/>
                  <table>
                    <tr>
                      <th>Ticker-Symbol</th>
                      <th>Market Cap</th>
                      <th>Previous Close</th>
                    </tr>
                    <tr>
                    <td>
                      <Link to='/details/' state={{

                        setState: this.state.symbol, 
                        companyName: this.state.companyName, 
                        previousClose: this.state.previousClose,
                        marketCap: this.state.marketCap,
                        change: this.state.change,
                        Yearweekhigh: this.state.Yearweekhigh,
                        Yearweeklow: this.state.Yearweeklow,
                        avgTotalVolume: this.state.avgTotalVolume,
                        peRatio: this.state.peRatio

                        }}>
                          {this.state.symbol}</Link>


                        </td>
                      <td>{this.state.marketCap}</td>
                      <td>{this.state.previousClose}</td>
                    </tr>
                  </table>
              </div>
              <div>
                {
                  this.state.topStocks.length && this.state.topStocks.map(stock => (
                  <h1>{stock.symbol}</h1>
                  ))
                }
              </div>
          </Layout>
      )
  }
}

chartData.js

import React from 'react'
import Plot from 'react-plotly.js'

class Stock extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            stockChartXValues: [],
            stockChartYValues: [],
        };
    }

    componentDidMount() {
        this.fetchStock();
    }

    fetchStock() {
        const pointerToThis = this;
        const API_KEY = '**************************';
        let API_CALL = `https://cloud.iexapis.com/stable/stock/aapl/chart/5y?token=${API_KEY}`;
        let stockChartXValuesFunction = [];
        let stockChartYValuesFunction = [];

        fetch(API_CALL)
        .then(function (response) {
            return response.json();
        })
        .then(function (data) {

            for (var x in data) {
                stockChartXValuesFunction.push(x);
                stockChartYValuesFunction.push(
                    data[x]['uOpen']
                );

                pointerToThis.setState({
                    stockChartXValues: stockChartXValuesFunction,
                    stockChartYValues: stockChartYValuesFunction,
                });
            }


        })
    }


    render() {
        return (
            <div>
                <Plot
                data={[
                    {
                        x: this.state.stockChartXValues,
                        y: this.state.stockChartYValues,
                        type: "scatter",
                        mode: "lines+markers",
                        marker: {color: "red"}
                    },
                ]}
                layout={{ width: 720, height: 440, title: "A Fancy Plot"}}
                />
            </div>
        )
    }
}

export default Stock
Ergin

In React if you need to share data between components the best approach is to use state and props to communicate the data. In this case your best bet is probably to store whatever variables you need to share as state in your parent or root component, then you can pass both the state data and setter functions to another other components in your app through properties.

For example:

    function Welcome(props) {
      return <h1>Hello, {props.name}</h1>;
    }

    function Bye(props) {
      return <h1>Bye, {props.name}</h1>;
    }

    function App() {
        constructor(props) {
          super(props);
          this.state = {
              name: '',
          };
        }
      return (
        <div>
          <Welcome name="Sara" />
          <Welcome name="Cahal" />
          <Bye name="Edite" />
        </div>
      );
    }

This is the official approach recommend in the official React docs, see section The Data Flows Down section.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How can I share/persist data/status across webdriverio specs?

How can i share data across multiple fragments in application?

How can I use a variable globally in js (across many files)?

How can I access and modify a global variable across multiple files?

How can I share references across threads?

How can I share variable values between different classes?

How can I reuse variable values across components in react

How can I share a local storage token across the same domain but a different host?

How to share a variable between epics that are in different files?

How to avoid share of variable across different user in singleton Class

In python, how to share (the reference of) a variable as attributes across different objects?

Python: How to share class variable logic across different classes?

How to share a variable across multiple source files in C++?

Can I share a component instance across multiple trees in React?

Docker Data Volume Container - Can I share across swarm

How can I generate a new variable that is the difference in value of the same variable across different years?

How to share data across Angular 2 Table component, so that each can have different data but use only same table component?

Can I share files/data through App Groups but in different developer accounts applications?

Global variables in Python to share variable across files

How can I share one resource across Node clusters

How can I share a Visual Studio project across computers easily?

How can I create a wifi hotspot and share my localhost across

How do I share data across controllers in AngularJS?

Share values and events across different components in React

Share data across different components in Vuejs

How can I use the Storage Transfer Service to copy data across buckets in different projects?

How do I share weights across different RNN cells that feed in different inputs in Tensorflow?

How can I use different sql files with Data for different test files?

How to share cookie across different domains NodeJS