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>
question from:
https://stackoverflow.com/questions/65851197/react-how-can-i-pass-api-data-from-one-component-to-another-in-a-different-js