zedunaid
zedunaid

Reputation: 5

Getting Undefined,NaN displayed after correct output is obtained

Error

Additional Undefined & Nan displayed

I have console.log state of the array which stores response value from api, It is giving me expected result, when I am parsing this response and using String, float operation on the parsed data, It is adding additional undefined,NaN %.

Console

Console of the response state

Code

import React from 'react';
import { StyleSheet, Text, View,TextInput } from 'react-native';
import axios from 'axios';

export default class OutputScreen extends React.Component {
  constructor(props) {
    super(props);
    this.renderCategory = this.renderCategory.bind(this);
    this.state={watdata:[]};
}

  componentWillMount()
  {
    const {state} = this.props.navigation;

  axios.post('https://app.accumulate65.hasura-app.io/api2',
  {
     username:'*****',
    type:state.params.inp,
    input:state.params.statement
   })
 .then(response =>this.setState({watdata:Object.values(response.data)})) 
 .catch(error => {
  console.log(error.response)
});

  }
  renderCategory()
  {
  return this.state.watdata.map((data)=>(<View style={{marginLeft:5}}>
   <Text>{String(data[0].label).substring(String(data[0].label).lastIndexOf("/") + 1, String(data[0].label).length)}                                {parseFloat(String(data[0].score)).toFixed(4)*100} %</Text>
   <Text>{String(data[1].label).substring(String(data[1].label).lastIndexOf("/") + 1, String(data[1].label).length)}                                {parseFloat(String(data[1].score)).toFixed(4)*100} %</Text>
   <Text>{String(data[2].label).substring(String(data[2].label).lastIndexOf("/") + 1, String(data[2].label).length)}                                {parseFloat(String(data[2].score)).toFixed(4)*100} %</Text>
   </View>));


  }


  render() {
    console.log(this.state);
    if(!this.state.watdata){
      return null;
  }
    return (
      <View>
         <Text style={{fontWeight:"bold",marginLeft:5}}>Your Results: </Text>
        <Text style={{fontWeight:"bold",marginLeft:5}}>Category Name                Confidence</Text>
        <View>{this.renderCategory()}</View>
      </View>
    );
  }
}

Upvotes: 0

Views: 1349

Answers (1)

Kyle
Kyle

Reputation: 3318

watdata is an array with two entries -- the first is a list of the label/score objects with 3 members. The second entry in the top-level watdata array is a string you redacted. When you map over watdata in your renderCategory method, you have two elements, and you look at indices 0, 1, and 2 of for each element, which causes you to have six entries total. The last three are all undefined though because your second element in watdata is a string.

Upvotes: 1

Related Questions