Error: Objects are not valid as a React child (found: object with keys {sds, id}). If you meant to render a collection of children, use an array instead.
import React, {Component} from 'react';
import axios from "axios";
class Post extends Component {
constructor() {
super();
this.state={
postData : "",
postResult : " "
}
}
onChangeHandler=(event)=>{
var mydata= event.target.value;
this.setState({postData:mydata})
}
onClickHandler=()=>{
axios.post('http://jsonplaceholder.typicode.com/posts',this.state.postData)
.then(response=>{
this.setState({postResult:response.data})
})
.catch(error=>{
alert("something wrong")
})
}
render() {
return (
<div>
<p>{this.state.postResult}</p>
<input onChange={this.onChangeHandler} type="text"/>
<button onClick={this.onClickHandler}>Post</button>
</div>
);
}
}
export default Post;
based on jsonplaceholder your response.data
will be an object following the structure:
{title: "myTitle", body: "myBody", id: 101}
this way this.state.postResult
will be an object and you can't pass an object to render which results in the error experienced. Instead you can extract title
and body
from postResult
for example:
render() {
const { title, body } = this.state.postResult
return (
<div>
<h1>Title: {title}</h1>
<p>Body: {body}</p>
<input onChange={this.onChangeHandler} type="text"/>
<button onClick={this.onClickHandler}>Post</button>
</div>
);
}