0

I am trying to display JSON data on my screen, the integer 4 to be exact.

But, I am receiving a JSON Parse Error.

I've posted and that works fine as in Webhooksite says it successfully posted. Also, it "gets" fine, but the data doesn't display. Please help!

// JSON Data

{
    "cheetosamount": 4,
    "cookiesvalue": 2
}
export default class ChooseDeliveries extends Component {

  constructor(props){
    super(props);
    this.state = {
      isLoading: true,
      dataSource: null
    }
  }
  componentDidMount(){
    this.handleGetRequest();
  }

  handleGetRequest() {
    fetch ('https://webhook.site/e61dd236-92d5-4b3b-882b-a50d6add6cd3',{
      method: 'GET',
    })
    .then(response => response.json())
    .then(responseJson => {
      this.setState({
        dataSource: JSON.parse(responseJson),
        isLoading: false,
      })
    })
    .catch(error => {
      console.error(error);
    });
  };


  render(){
    if(this.state.isLoading){
      return(
        <View style={{flex: 1, padding: 20}}>
          <ActivityIndicator/>
        </View>
      )
    } else {
      return(
        <View style={{flex: 1, paddingTop:20}}>
          <Text>
            {this.state.dataSource.cheetosamount}
          </Text>
        </View>
      );
    }
  } 
} 

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});
Jae Lee
  • 67
  • 1
  • 10

1 Answers1

0

I believe its because that 'JSON' that you are getting is already an object and there's no need for you to parse it.

More indepth explaination provided here SyntaxError: Unexpected token o in JSON at position 1

Try the following in your chrome console

let c ={
    "cheetosamount": 4,
    "cookiesvalue": 2
}

c.cheetosAmount

So essentially all you have to do is

 this.setState({
        dataSource: responseJson,
        isLoading: false,
      })

LoXatoR
  • 529
  • 5
  • 17