Ycon Ycon - 2 months ago 18
JSON Question

Using fetch to post JSON data

I'm trying to do a post of multiple points of data from a form input.

However, the form data doesn't reach json output payload (I checked the network output). It seems to never get triggered.

If there's a better way to re-write this- I am open to it

I've put it all into Codepen- http://codepen.io/yarnball/pen/LRVgpo?editors=1011

The data needs to be posted in this exact way:

{
"title": "SAMPLE",
"tag": [
{
"name": "Movie",
"taglevel": 1,
}
],
"info": []
}


Post method



var Postapi = React.createClass({
componentWillMount () {
var form = document.querySelector('form')
return fetch('http://localhost:8000/api/Data/', {
method: 'POST',
body: JSON.stringify({
title: this.state.itemtitle,
tag:[
{name:this.state.tagtitle,
taglevel:this.state.taglevel}
],
info:[]
})
})


},

Sample return



<form onSubmit={this.handleSubmit}>
...
<input
placeholder="Item Title"
type="text"
itemtitle={this.state.itemtitle}
onChange={this.handleChange}
/>


Initial state & submit



getInitialState: function() {
return {
itemtitle: [],
tagtitle: [],
taglevel: [],
tagoptions: Exampledata
};
},

handleChange: function(event) {
this.setState({itemtitle: event.target.itemtitle});
this.setState({tagtitle: event.target.tagtitle});
this.setState({tagname: event.target.tagname});
},
handleSubmit: function(e) {
e.preventDefault();
var itemtitle = this.state.itemtitle
var tagtitle = this.state.tagtitle
var taglevel = this.state.taglevel
this.setState({itemtitle: '', text: ''});
},

Answer

you must call your fetch function in handlesubmit function...according to this link , componentWillMount : is executed before rendering, on both server and client side. so your form is empty. you need read more about react life cycle.

Comments