Reputation: 325
After I execute a query in the console I can see: {data:{action: [...]}
. How can I assign that data to a variable in a React component?
Trying this but it is not working:
class MyGraph extends React.Component {
constructor(props) {
super(props);
this.state = {
nodes: this.data
Upvotes: 0
Views: 44
Reputation: 3395
Have some falsy or empty initial value for state.node
. Then fetch the data in componentDidMount
- on success, update state.node
with your actual data. That data can also be passed down to child components. Example:
class MyGraph extends React.Component {
constructor(props) {
super(props);
this.state = {
nodes: null,
}
}
componentDidMount() {
// w/e your fetch function is. I'm assuming your method uses promises.
fetchDataSomehow().then((response) => {
this.setState({nodes: response.data}) // or whatever property has the nodes
})
}
render() {
const nodes = this.state.nodes;
return (
<LoadingIcon isVisible={!nodes}>
{(nodes || []).map((node) => (
<MyCircle key={node.someUniqueId} node={node} /> // access `node` inside the `<MyCircle />` component using `this.props.node`
))}
</LoadingIcon>
)
}
}
You'll need to handle what happens/renders while the data is still loading (e.g the made-up <LoadingIcon />
component).
Upvotes: 1