Understanding how Ajax success callback updates state in this ReactJS example - javascript

I am working thought the Reactjs Tutorial. I am trying to understand how the CommentForm component submits (or updates the server) with the data it has collected via passing it up to the CommentBox.
Here are the two components that work for reference:
var CommentForm = React.createClass({
handleSubmit: function(e) {
e.preventDefault();
var author = React.findDOMNode(this.refs.author).value.trim();
var text = React.findDOMNode(this.refs.text).value.trim();
if (!text || !author) {
return;
}
this.props.onCommentSubmit({author: author, text: text});
React.findDOMNode(this.refs.author).value = '';
React.findDOMNode(this.refs.text).value = '';
return;
},
render: function() {
return (
<form className="commentForm" onSubmit={this.handleSubmit}>
<input type="text" placeholder="Your name" ref="author" />
<input type="text" placeholder="Say something..." ref="text" />
<input type="submit" value="Post" />
</form>
);
}
});
var CommentBox = React.createClass({
loadCommentsFromServer: function() {
$.ajax({
url: this.props.url,
dataType: 'json',
cache: false,
success: function(data) {
this.setState({data: data});
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
handleCommentSubmit: function(comment) {
$.ajax({
url: this.props.url,
dataType: 'json',
type: 'POST',
data: comment,
success: function(data) {
this.setState({data: data});
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
getInitialState: function() {
return {data: []};
},
componentDidMount: function() {
this.loadCommentsFromServer();
setInterval(this.loadCommentsFromServer, this.props.pollInterval);
},
render: function() {
return (
<div className="commentBox">
<h1>Comments</h1>
<CommentList data={this.state.data} />
<CommentForm onCommentSubmit={this.handleCommentSubmit} />
</div>
);
}
});
My source of confusion comes from handleCommentSubmit in the CommentBox component, specifically the Ajax success callback.
Since we set data: comment, data is now merely the comment the form collected. But on success we take data and do this.setState({data: data});. Wouldn't that be setting the state to only one comment (the one we collected in the form?). Wouldn't we need to pull from the server to get all of the data, including the POST we just made with something like loadCommentsFromServer? How does this work?

Since we set data: comment, data is now merely the comment the form
collected. But on success we take data and do this.setState({data:
data});. Wouldn't that be setting the state to only one comment (the
one we collected in the form?).
No, in the example, the comment passed in to the function is setting the data property for the ajax request. The data parameter in the success callback is the data from the ajax response.
So, here they are setting the data state property to whatever the server responds with. I think the example assumes that the server is reflecting the same comment, but this allows the server to save the comment during the HTTP call.

Related

Display array element ReactJS

UPD: How can I display elment of the array in my component (WeatherCityName - h2)? It can be seen that the array is loaded, but when I point out the property - an error occurs, it may be a problem in the syntax?
var WeatherBox = React.createClass({
handleWeatherSubmit: function(text) {
$.ajax({
url: this.props.url,
dataType: 'json',
type: 'POST',
data: 'cityName=' + text,
success: function(data) {
this.setState({data: data});
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
getInitialState: function() {
return {data: []};
},
render: function() {
return (
<div className="wetherBox">
<h1> Weather</h1>
<WeatherForm onWeatherSubmit={this.handleWeatherSubmit} />
<WeatherCityName data={this.state.data[0]} />
<WeatherList data={this.state.data} />
</div>
);
}
});
var WeatherCityName = React.createClass({
render: function(){
return(
<h2>{this.state.data[0].cityName}</h2>
);
}
});
Sure, just put <h2>{weatherItem.cityName}</h2> directly in the <div>.
var WeatherList = React.createClass({
render: function() {
var weatherNodes = this.props.data.map(function(weatherItem) {
return (
<div className="city-item-with-title">
<h2>{weatherItem.cityName}</h2>
<WeatherItem
cityid={weatherItem.cityid}
type={weatherItem.type}
src={weatherItem.src}
temp={weatherItem.temp}
tempFrom={weatherItem.tempFrom}
tempTo={weatherItem.tempTo}
key={weatherItem.id}
/>
</div>
);
});
return (
<div className="weatherList">
{weatherNodes}
</div>
);
}
});
Edit: I'm not sure which weather item you want to use as a title, perhaps this.props.data[0]?
Edit 2: Just assumed you want to use the first weather item.
Edit 3: One title for each weatherItem, grouped inside a div together with the corresponding weatherItem.

React Tutorial and Sinatra API: Uncaught TypeError: this.props.data.map is not a function

I know, there are hundreds of questions with the same title, but nothing helped my get a solution for my problem. so I worked through the official react js tutorial and build a small API with sinatra to test things.
so everything works really good. except of one error I see in the console when submitting a new "Joke" (called them jokes instead of comments ;)) via AJAX.
app.js:66 Uncaught TypeError: this.props.data.map is not a function
This happens when I click on submit. I logged the state when submitting the form and everything seems to be okay (array with the temporary objects).
so the new Joke is being added and written to the database. It works but i don't know why I'm getting the Uncaught TypeError in the console.
thanks in advance!
var JokeBox = React.createClass({
loadJokesFromServer: function() {
$.ajax({
url: this.props.url,
dataType: 'json',
cache: false,
success: function(data) {
this.setState({data: data});
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
handleJokeSubmit: function(joke) {
var jokes = this.state.data;
var tmpJoke = jQuery.extend({}, joke)
tmpJoke.id = new Date();
tmpJoke.likes = 0;
jokes.unshift(tmpJoke);
this.setState({data: jokes}, function(){
$.ajax({
url: this.props.url,
dataType: 'json',
type: 'POST',
data: joke,
success: function(data) {
this.setState({data: data});
}.bind(this),
error: function(xhr, status, err) {
this.setState({data: jokes});
console.error(this.props.url, status, err.toString());
}.bind(this)
});
});
},
getInitialState: function() {
return {data: []};
},
componentDidMount: function() {
this.loadJokesFromServer();
setInterval(this.loadJokesFromServer, this.props.pollInterval);
},
render: function() {
return (
<div className="jokes">
<h1>Jokes</h1>
<JokeForm onJokeSubmit={this.handleJokeSubmit} />
<JokeList data={this.state.data} />
</div>
);
}
});
var JokeList = React.createClass({
render: function() {
var jokeNodes = this.props.data.map(function(joke) {
return (
<Joke content={joke.content} key={joke.id} likes={joke.likes} />
);
});
return (
<div className="jokeList">
{jokeNodes}
</div>
);
}
});
var JokeForm = React.createClass({
getInitialState: function() {
return {content: ''};
},
handleContentChange: function(e) {
this.setState({content: e.target.value});
},
handleSubmit: function(e) {
e.preventDefault();
var content = this.state.content.trim();
if (!content) {
return;
}
this.props.onJokeSubmit({content: content});
this.setState({content: ''});
},
render: function() {
return (
<form className="jokesForm" onSubmit={this.handleSubmit}>
<input
type="text"
placeholder="Your Joke!"
value={this.state.content}
onChange={this.handleContentChange}
/>
<input type="submit" value="Send joke" />
</form>
);
}
});
var Joke = React.createClass({
render: function() {
return (
<div className="joke">
<p className="jokeContent">{this.props.content}</p>
<p className="jokeLikes">{this.props.likes}</p>
</div>
);
}
});
ReactDOM.render(
<JokeBox url="/api/jokes" pollInterval={2000} />,
document.getElementById('app')
);
// EDIT
So I played around with the sample tutorial repo from the tutorial. I log the data in the handleSubmit in the success function right before the state is set. And I figured out: my data is ja object of the actual new Joke, in the sample tutorial it is an array of all comments. How could this be? I can't find my mistake...
try
handleJokeSubmit: function(joke) {
let {data}= this.state;
$.post(this.props.url, joke, res=>{
this.setState({data:[res,...data]});
})
.fail( err=>alert('Error: ' + err.responseText));
}
///EDIT es5
handleJokeSubmit: function(joke) {
var data = this.state.data;
$.post(this.props.url, joke, function(res){
this.setState({data:[res].concat(data)});
}.bind(this))
.fail( function(err){alert('Error: ' + err.responseText)});
}

ReactJS tutorial- Comment form not posting to local server

I'm trying to set up a local server that hosts a comment submission system (as per the React tutorial). In the CommentForm class, I want to have the form handle a comment submission, which uses a POST request to modify a local file called comments.json. This POST request isn't working. Can anyone figure out why? I have the following code (I have excluded the Comment and CommentList classes to reduce clutter but I will include them if it will be helpful). The console.log line that prints "submitting" is never executed:
var Comment = React.createClass({
// code excluded for brevity
});
var CommentForm = React.createClass({
handleSubmit: function(e) {
console.log("submitting");
e.preventDefault();
var author = this.refs.author.value.trim();
var text = this.refs.text.value.trim();
if (!text || !author) {
return;
}
this.props.onCommentSubmit({author: author, text: text});
this.refs.author.value = '';
this.refs.text.value = '';
return;
},
render: function() {
return (
<form className = "commentForm">
<input type="text" placeholder="Your name" ref="author"/>
<input type="text" placeholder="Say something..." ref="text"/>
<input type="submit" value="Post"/>
</form>
);
}
});
var CommentList = React.createClass({
// code excluded for brevity
});
var CommentBox = React.createClass({
loadCommentsFromServer: function() {
$.ajax({
url: this.props.url,
dataType: 'json',
cache: false,
success: function(data) {
this.setState({data: data});
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
getInitialState: function() {
return {data: []};
},
handleCommentSubmit: function(comment) {
$.ajax({
url: this.props.url,
dataType: 'json',
type: 'POST',
data: comment,
success: function(data) {
this.setState({data: data});
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
componentDidMount: function() {
this.loadCommentsFromServer();
setInterval(this.loadCommentsFromServer, this.props.pollInterval);
},
render: function() {
console.log("rendering box");
return (
<div className="commentBox">
<h1>Comments</h1>
<CommentList data={this.state.data} />
<CommentForm onCommentSubmit={this.handleCommentSubmit} />
</div>
);
}
});
ReactDOM.render(
<CommentBox url="/api/comments" pollInterval = {2000} />,
document.getElementById('content')
);
You forgot to bind the onSubmit event of the form the handler.
<form className="commentForm" onSubmit={this.handleSubmit}>

File upload component sending two ajax requests

I'm new to react I've cobbled this react component together from different pieces i've found on the web. It's supposed to upload a file via ajax on submit. For some reason it's double firing. So when I hit submit my server is getting two requests instead of one.
Does anything stand out that a react beginner might miss?
/** #jsx React.DOM */
var $ = require("jquery")
var React = require('react');
var FileForm = React.createClass({
getInitialState: function() {
return {
myFileName: "",
myFileHandle: {}
};
},
handleChange: function(event) {
this.setState({
files: [event.target.files[0]] // limit to one file
});
},
handleSubmit: function(e) {
e.preventDefault();
var data = new FormData();
$.each(this.state.files, function(i, file) {
data.append('file-'+i, file)
})
$.ajax({
url: "/api/content/csv/upload.json",
data: data,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data) {
this.refs.fileInput.value = null
console.log(this.refs.fileInput)
console.log(data)
}.bind(this),
error: function(xhr, status, err) {
console.log(xhr)
console.log(status)
console.log(err)
}.bind(this)
})
},
render: function() {
return (
<form onSubmit={this.handleSubmit} method="POST" encType="multipart/form-data">
<input ref="fileInput" type="file" onChange={this.handleChange}/>
<input type="submit" value="Submit"/>
</form>
)
}
})
module.exports = FileForm

ReactJS Props and bubbling

I'm having a hard time understanding why I can't do something like this.
loadPostsFromServer: function() {
$.ajax({
url: '/allPosts',
dataType: 'json',
success: function(data) {
console.log(data);
this.setState({posts:data, items:data});
//this.setState({items:data});
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url,status, err.toString());
}.bind(this)
});
},
loadUserFromServer: function() {
$.ajax({
url: '/user',
dataType: 'json',
success: function(data) {
this.setState({user:data.local});
//console.log(this.state.user);
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url,status, err.toString());
}.bind(this)
});
},
getInitialState: function() {
return {
posts: [],
items: [],
user: []
}
},
componentDidMount: function() {
this.loadPostsFromServer();
this.loadUserFromServer();
//this.setState({items: this.state.posts});
//setInterval(this.loadPostsFromServer, this.props.pollInterval);
},
render: function() {
<div className="Posts">
<List user={this.state.user} posts={this.state.items} />
</div>
}
Where List can be something like this and can't do the this.props.user print
var List = React.createClass({ //has to be called list
render: function() {
return (
<p>{this.props.user}</p>
<ul>
{
this.props.posts.map(post){
return (<p>{post.title}</p>)
})
}
</ul>
)
}
});
but can do this:
var List = React.createClass({
render: function() {
return (<p>{this.props.user}</p>)
}
});
Basically I'm passing two props in my real function, and the ajax call is delivering down a array user, with user info, and array post with post info. I can display the post info fine, and the user info is complete as well, however I cannot actually display the user info received from the ajax get call. I printed out the state of the array as well and it was complete and filled. However passed down it would return messages like cannot read {this.props.user.firstName} and such, however writing it the second way and not including posts, it works fine. How can I use both props in a map function?
Be careful, in render function, you always need a wrap tag to make React work. You should add <div> tag to the render of List component.
var List = React.createClass({ //has to be called list
render: function() {
return (
<div> <-- ALWAYS HAS A WRAP TAG
<p>{this.props.user}</p>
<ul>
{
this.props.posts.map(post){
return (<p>{post.title}</p>)
})
}
</ul>
</div>
)
}
});
This code below works because there is <p> to wrap contents.
var List = React.createClass({
render: function() {
return (<p> <-- WRAP TAG
{this.props.user}
</p>)
}
});

Categories

Resources