1

I'm trying to use d3 select some elements, append g and generate an axis inside of svg.

I've debugged each step inside of renderWeather and it seems that d3.json did get executed but I see no elements rendering. I couldn't figure out why.

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


 export default class Weather extends Component { 

 componentDidMount () {
    this.renderWeather()
 }

 componentDidUpdate () {
    this.renderWeather()
 }

 renderWeather = () => {

  const tmp = (d) => {
  const xScale = d3
  .scaleLinear()
  .domain([1, 10])
  .range([20, 470])

  const yScale = d3
  .scaleLinear()
  .domain([0, 40])
  .range([480, 20])

  const xAxis = d3
  .axisBottom()
  .scale(xScale)
  .tickSize(480)
  .ticks(8)

  d3.select(this.refs.container)
  .append('g')
  .attr('id', 'xAxisG')
  .call(xAxis)

  d3.select(this.refs.container)
  .append('rect')
  .style('width', 100)
  .style('height', 100)

// I haven't used any data, just trying to make it work first
}


  // dummy url here
  d3.json('https://google.com', tmp)
}

render() {
 return (
  <svg ref="container">
  </svg>
)

} }

I expect the xAxis in the bottom but could see nothing inside <svg></svg> Why is this?

wentjun
  • 40,384
  • 10
  • 95
  • 107
jen007
  • 1,389
  • 3
  • 15
  • 19

1 Answers1

1

The D3.js D3-fetch module uses the Fetch API to handle HTTP requests.

Therefore, to load and parse the JSON object, you will need to resolve the promise which was returned within the then() statement.

d3.json('some-path').then(response => {
  console.log(response); 
  // handle the rest here
  tmp(response);
});

Likewise, the anonymous function from tmp, within the renderWeather() method, should be called within the then() statement, since the rendering of the chart is dependent on the data returned by d3.json().

wentjun
  • 40,384
  • 10
  • 95
  • 107
  • 1
    This `d3.json('https://google.com').then(d => tmp(d))` works – jen007 Aug 04 '19 at 19:17
  • @jen007 ah, yes I just realised you created an anonymous function. I will update my answer accordingly. – wentjun Aug 04 '19 at 19:20
  • Is there any way of exposing json response `d` as a global variable or this is the only way of accessing `d`? – jen007 Aug 04 '19 at 19:27
  • 1
    You may assign try assigning it to a property within your class! This way, you can access it anywhere else in the class – wentjun Aug 05 '19 at 13:35
  • `d3.json('https://google.com').then(d => this.data = d)` will have `this.data` available for entire react component. Thanks!! – jen007 Aug 05 '19 at 16:35