0

Lets say I want to pass the data from the getData axios request in my code below to another function located in a different file in my react app.

export default function Bucket() {

    const { slug } = useParams();
    const classes = useStyles();

    const [data, setData] = useState({ bucket: [] });

    useEffect(() => {
        axiosInstance.get('bucket/' + slug + '/').then((res) => {
            setData({ bucket: res.data });
            console.log(res.data);
        });
    }, [setData, slug]);

    const getData = () => {
        axiosInstance
        .get('bucket/fin-data/' + slug).then((response) => {
                console.log(response)
            })
    }

    return (
        <Container component="main" maxWidth="md">
            <CssBaseline />
            <div className={classes.paper}></div>
            <div className={classes.heroContent}>
                <Container maxWidth="sm">
                    <Typography
                        component="h1"
                        variant="h2"
                        align="center"
                        color="textPrimary"
                        gutterBottom
                    >
                        {data.bucket.name}
                    </Typography>
                    <Typography
                        variant="h5"
                        align="center"
                        color="textSecondary"
                        paragraph
                    >
                        {data.bucket.about}
                    </Typography>
                    <SymbolInput/>
                </Container>
                <button onClick={getData}>get data</button> 
            </div>
        </Container>
    );
}

Instead of calling my API twice, how would I go about passing that data to another component? Most of the examples I'm looking at use classes, I would like to use functions instead.

For example, how can I pass that data to this chart, specifically where I marked . Pseudocode is welcomed, also please change around the example chart if needed:

const BarChart = () => {
  return (
    <div>
      <Pie
        data={{
          labels:<HERE>,
          datasets: [
            {
              label: '# of votes',
              data: <HERE>,
              backgroundColor: [
                'rgba(255, 99, 132, 0.2)',
                'rgba(54, 162, 235, 0.2)',
                'rgba(255, 206, 86, 0.2)',
                'rgba(75, 192, 192, 0.2)',
                'rgba(153, 102, 255, 0.2)',
                'rgba(255, 159, 64, 0.2)',
              ],
              borderColor: [
                'rgba(255, 99, 132, 1)',
                'rgba(54, 162, 235, 1)',
                'rgba(255, 206, 86, 1)',
                'rgba(75, 192, 192, 1)',
                'rgba(153, 102, 255, 1)',
                'rgba(255, 159, 64, 1)',
              ],
              borderWidth: 1,
            },
          ],
        }}
        height={400}
        width={600}
        options={{
          maintainAspectRatio: false,
          scales: {
            yAxes: [
              {
                ticks: {
                  beginAtZero: true,
                },
              },
            ],
          },
          legend: {
            labels: {
              fontSize: 25,
            },
          },
        }}
      />
    </div>

1 Answer 1

2

In React, You can pass the data two way most commonly:

1.

  • Pass a callback function to from common main to child component.
  • When async action is done, execute it with data.
  • Give it the data with props to another component.
export default function Bucket({ onGetData }) {

    const { slug } = useParams();
    const classes = useStyles();

    const [data, setData] = useState({ bucket: [] });

    useEffect(() => {
        axiosInstance.get('bucket/' + slug + '/').then((res) => {
            setData({ bucket: res.data });
            console.log(res.data);
        });
    }, [setData, slug]);

    const getData = () => {
        axiosInstance
        .get('bucket/fin-data/' + slug).then((response) => {
                onGetData(response);
                console.log(response)
            })
    }

    return (
        <Container component="main" maxWidth="md">
            <CssBaseline />
            <div className={classes.paper}></div>
            <div className={classes.heroContent}>
                {...}
                <button onClick={getData}>get data</button> 
            </div>
        </Container>
    );
}
export default function MainComponent() {

    const [data, setData] = useState({});
      
    const onGetData = (result) => {
        setData(result);
    };

    return (
        <MainComponent>
          <Bucket onGetData={onGetData} />
          <BarChart data={data} /> 
        </MainComponent>
    );
}
  1. You can pass with any state Manager: Redux, Mobx e.g.
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you this makes a lot of sense. Generally speaking, which option would you recommend, 1 or 2?
If your application is have a simple architecture, data passing with props is enough for you. Else you have a complex application, state managers will helps you for stop props chaining.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.