Home > Enterprise >  Pulling data from function and adding it to a global variable in Javascript
Pulling data from function and adding it to a global variable in Javascript

Time:08-17

I'm building a webapp in React.js and I'm trying to pass data from a child component back up to the parent. I am passing the data back up successfully but can't manage to extract the relevant data to become a global variable. I would really appreciate anyone's help. I know that I am returning the correct data based on the console.log.

I am trying to extract 'data' from the 'pull_data' function and add it to the global 'year' variable.

Here is my code:

import React, { useEffect, useState, useContext } from "react";
import { useAuthState } from "react-firebase-hooks/auth";
import { useNavigate } from "react-router-dom";
import { auth } from "../firebase";
import Header from "../components/headerTeamList";
import Grid from "@material-ui/core/Grid";
import { makeStyles } from "@material-ui/core/styles";
import TeamList from "../components/teamList";
import { getTeams } from "../api/football-api";
import Menu from "../components/dropdownMenu";

const useStyles = makeStyles({
  root: {
    padding: "60px",
  },
});

function Dashboard() {
  const [user, loading, error] = useAuthState(auth);
  const navigate = useNavigate();
  const classes = useStyles();
  const [teams, setTeams] = useState([]);

  const pull_data = (data) => {
    console.log(data);
    return data;
  }

  const year = 2016 //need to update

  useEffect(() => {
    if (loading) return;
    if (!user) return navigate("/");
  }, [user, loading]);

  useEffect(() => {
    getTeams(year).then((json) => {
      setTeams(json.response[0].league.standings[0]);
    });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [year]);

  return (
    <Grid container className={classes.root}>
      <Grid item xs={12}>
        <Header title={"Home Page"} />
        <Menu func={pull_data}></Menu>
      </Grid>
      <Grid item container spacing={5}>
        <TeamList teams={teams}></TeamList>
      </Grid>
    </Grid>
  );
}

export default Dashboard;

CodePudding user response:

You can make year a state variable and set it from pull_data:

const [year, setYear] = useState(2016)
const pull_data = data => {
  setYear(data)
}
  • Related