Reputation: 1359
I am receiving the data from server but not able to parse it. when i parse i am geeting an error as " Unexpected token u in JSON at position 0 at JSON.parse ()".
import React from 'react';
import axios from 'axios';
class Premontessori extends React.Component{
constructor(props){
super(props);
this.state={
post:[]
};
}
componentDidMount(){
axios.get('http://localhost:8080/list')
.then(data => this.setState({post:data} )
);
}
render(){
return(
<div>
{JSON.parse(this.state.post.data)}
</div>
);
}
}
export default Premontessori;
Upvotes: 0
Views: 341
Reputation: 1073968
This:
axios.get('http://localhost:8080/list')
.then(data => this.setState({post:data} )
...will set your state to {post: ...}
where ...
is the value of data
, which will presumably be a string or a parsed object tree, depending on whether axios.get
automatically parses JSON when it receives it or not.
If it's a string, you need to parse it with JSON.parse
. Then either use it directly:
.then(data => this.setState(JSON.parse(data) )
...or if it's really meant to be the value of post
, then:
.then(data => this.setState({post: JSON.parse(data)} )
If it's already parsed, then I'm guessing it shouldn't be the value of a post
, so:
.then(data => this.setState(data))
Upvotes: 1