0

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
7
  • how would you get the data? Commented Aug 18, 2018 at 4:36
  • That is what I am trying to figure out. I can see the data in console but don't know how to access it. Commented Aug 18, 2018 at 4:38
  • What do you mean by "access a query in the console"? What is the query? Why can't you just put the same code directly into your React component? Commented Aug 18, 2018 at 4:39
  • share the whole component Commented Aug 18, 2018 at 4:40
  • if you can see it in console, try to find the console.log() statement that is putting it there. also, there is a nice React extension for Chrome browser that can be helpful for this sort of thing. Commented Aug 18, 2018 at 4:40

1 Answer 1

1

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).

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I'll see what I can do with this and let you know how it goes.

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.