1

I want to fetch numerical values through API call and represent them in graph using 'react-native-chart-kit', but its producing error data[0].toFixed is not a function. How to resolve this error?click here to view error

class SecondActivity extends Component {

 constructor(props){
   super(props);
   this.state={a:"",b:""}
 }

 componentDidMount(){
   this.graph = setInterval( () => this.GetGraph(),1000);
 }

 GetGraph(){
   var jsondata;
  fetch('api here', {
    method: 'GET'
 })
 .then((response) => response.json())
 .then((responseJson) => {
   
   this.setState({
       jsondata: responseJson,
       a:responseJson[0].val,
       b:responseJson[1].val,})
   }) 
 .catch((error) => {
    console.error(error);
 });   } 

  render() {
      if(!this.state.a) {
    return <ActivityIndicator/>
  }
    return (
      <View>
        <LineChart
          data={{
            labels: [
              '1',
              '2', ],
            datasets: [
              {
                data: [
                  this.state.a,
                  this.state.b,                                 
                ],
              },                ],              }}
          width={Dimensions.get('window').width} 
          height={250}
          yAxisLabel="a"
          yAxisInterval={1}/>
      </View>);}}

1 Answers1

0

I don't know react-native-chart-kit but since toFixed() is a method on Number, I suppose responseJson[0].val and/or responseJson[1].val may contain (some?) other values then numbers.

Depending on the data, a workaround may be a conversion to numbers:

this.setState({
    jsondata: responseJson,
    a:responseJson[0].val.map(v => { /* return v converted to number */ },
    b:responseJson[1].val.map(v => { /* return v converted to number */ }
}) 

I won't provide a conversion here. Without knowing the possible values in your data, any proposal could be lossy (or just plain wrong).

Secondly, if the server is expected to send numbers, it should send numbers. This may be a bug, but there may also be a reason for sending numbers, e.g. to be able to submit numbers with high precision or sending fixed point decimals lossless. In this case, you have to be careful how to use these values in JavaScript.

If this is not the solution you should provide the raw JSON response for further inspection.

Sebastian B.
  • 2,141
  • 13
  • 21