I am trying to pass data from a button click event in ToolBarElement.js to GraphElement.js
The backend is using Flask to serve data on /data
route
It seems to build without errors, but it returns a blank screen if I include the line <p>{state.graph_data}</p>
in GraphElement.js
App.js
function App() {
const state = {
graph_data: 0,
}
return (
<div className="App">
<div className="App-body">
<div className="toolbar-element" style={{ top: "50px", left: "0px" }}>
<ToolbarElement props={state} />
</div>
<div className="graph-element" style={{ top: "50px", right: "0px" }}>
<GraphElement props={state} />
</div>
</div>
</div >
);
}
export default App;
ToolbarElement.js
function ToolbarElement(props) {
const { state } = props;
const [data, setdata] = useState({
lst: [],
});
const handleButtonClick = () => {
console.log('Button clicked!');
fetch("/data").then((res) =>
res.json().then((data) => {
// Setting a data from api
setdata({
lst: data,
});
})
);
state.graph_data = data.lst[0]; //Getting first data value from List
};
return (
<div style={{ height: '33.33%', backgroundColor: '#F0F0F0' }}>
<button onClick={handleButtonClick}>Click me!</button>
</div>
);
}
export default ToolbarElement;
GraphElement.js
function GraphElement(props) {
const { state } = props;
return (
<div style={{ height: '33.33%', backgroundColor: '#E8E8E8' }}>
<p>{state.graph_data}</p>
</div>
);
}
export default GraphElement;
The error I get in console is olbarElement.js:21 Uncaught TypeError: Cannot set properties of undefined (setting 'graph_data')
3
Answers
You’re close to the right answer. You’ve lifted shared state up into the
App
component. But you can’t just use a regular old object as state in theApp
component. You need to instead use theuseState
hook inApp
and passstate
andsetState
down into the child components.You can use Context to avoid prop drilling( passing data from multiple components until it reaches the component that needs it).
Read more at: avoiding prop drilling
Have you tried this?