0

could someone please tell me why I cant access the react.state in my d3.js function. I really cant figure out why.

import React, { Component } from 'react'
import * as d3 from 'd3';

class Treemap extends Component {
  constructor(props) {
    super(props);
    this.state = {
      test: 1
    }
this.drawTreeMap = this.drawTreeMap.bin(this)
  }

  componentDidMount() {
    this.drawTreeMap();
    console.log(this.state.test) // works fine
  }

  drawTreeMap() {
    Promise.all([
      d3.json("https://cdn.freecodecamp.org/testable-projects-fcc/data/tree_map/kickstarter-funding-data.json"),
      d3.json("https://cdn.freecodecamp.org/testable-projects-fcc/data/tree_map/movie-data.json"),
      d3.json("https://cdn.freecodecamp.org/testable-projects-fcc/data/tree_map/video-game-sales-data.json")
    ])
    .then(function(data) {
      let kickstarter = data[0];
      let movie = data[1];
      let videoGamesSaleData = data[2];

      console.log(this.state.test)  // does not work (Unhandled Rejection (TypeError): Cannot read property 'state' of undefined)

The first console.log(this.state.test) in the lifecycle method works, but the second one does not work. Is it because d3 does not cooperate with react state, or did i make a foolish mistake?

Best regards!!!

c0mmand0r
  • 33
  • 5
  • 2
    Does this answer your question? [Unable to access React instance (this) inside event handler](https://stackoverflow.com/questions/29577977/unable-to-access-react-instance-this-inside-event-handler) – Juan Marco Feb 19 '20 at 14:21
  • You need to bind `this` to your `drawTreeMap()` function inside your constructor. `this.drawTreeMap = this.drawTreeMap.bind(this);` – Jackson Feb 19 '20 at 15:42
  • Binding this in the constructor does not work. – c0mmand0r Feb 19 '20 at 16:16

1 Answers1

0

Can you try to return the Promise respond, as you can see on example : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

let promis = Promise.all([
      d3.json("https://cdn.freecodecamp.org/testable-projects-fcc/data/tree_map/kickstarter-funding-data.json"),
      d3.json("https://cdn.freecodecamp.org/testable-projects-fcc/data/tree_map/movie-data.json"),
      d3.json("https://cdn.freecodecamp.org/testable-projects-fcc/data/tree_map/video-game-sales-data.json")
    ])
    .then(function(data) {
      return data;
    });

console.log(promis[0]);
console.log(this.state.test)
eroll.maxhuni
  • 271
  • 2
  • 6