Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;

>Solution :

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

const [year, setYear] = useState(2016)
const pull_data = data => {
  setYear(data)
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading