Trying to read data from json dynamically using Highcharts in React. Throwing in the towel and appealing to SO for help.
Keep getting:
"Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0"
no matter where I put the file. Ejecting from create-react-app and changing the Webpack config was no help.
Network tab shows a 200 response.
JSON is valid. Have tried to read json from both src
and public
folder. Have tried using fetch
with headers and without. (Using with headers changes 200 to 404).
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
}
console.log(response.headers.get('Content-Type'))
returns text/html; charset=UTF-8
.
Have tried the solutions here and here.
Here's the component:
Chart.js
import React, { Component } from 'react';
import HighchartsReact from 'highcharts-react-official';
import Highcharts from 'highcharts';
const endpoint = '../public/dummy.json'
export default class Chart extends Component {
constructor(props) {
super(props);
this.state = {
// To avoid unnecessary update keep all options in the state.
chartOptions: {
chart: {
type: 'bar'
},
xAxis: {
title: {
text: 'X Axis'
}
},
yAxis: {
title: {
text: 'Y Axis'
},
min: 0,
max: 100
},
series: [
{ data: [6] }
],
plotOptions: {
series: {
point: {
events: {
mouseOver: this.setHoverData.bind(this)
}
},
name: 'Chart name'
}
}
},
hoverData: null
};
}
setHoverData = (e) => {
console.log(e)
// The chart is not updated because `chartOptions` has not changed.
this.setState({ hoverData: e.target.options.x })
}
updateSeries = () => {
// The chart is updated only with new options.
this.setState({
chartOptions: {
series: [
{ data: [Math.random() * 100]}
]
}
});
}
componentDidMount() {
// fetch(endpoint, {
// headers: {
// 'Accept': 'application/json',
// 'Content-Type': 'application/json'
// }
// })
fetch(endpoint)
.then((response) => {
response.json()
console.log(response.headers.get('Content-Type'))
})
.then(data => {
this.state.chartOptions.series[0].data = data;
this.setState({ data: data });
})
// .catch(error => {
// console.log('Error! ', error)
// })
}
render() {
const { chartOptions, hoverData } = this.state;
console.log('this.state: ', this.state)
return (
<div>
<HighchartsReact
highcharts={Highcharts}
options={chartOptions}
/>
<h3>Hovering over {hoverData}</h3>
<button onClick={this.updateSeries.bind(this)}>Update Series</button>
</div>
)
}
}
dummy.json
[
{
"first_name": "John",
"amount": 10
},
{
"fist_name": "Tim",
"amount": 8
}
]
index.js
import ReactDOM from 'react-dom';
import Chart from './Chart'
ReactDOM.render(<Chart />, document.getElementById('root'));