ReactJS AJAX best practice
I am currently trying to learn ReactJS and can't really find any consistent documentation (even the official docs look a bit messed up), especially around AJAX, it all seems a bit cobbled together. I've ended up using the JQuery $.get method which seems like a bit of a cheat.
I have the code below but just wondered if there was a cleaner way of dealing with simple AJAX calls? I'm also firing this off within componentDidMount which seemed the most logical, looking at the lifecycle.
Any help is welcomed!!
getInitialState: function () {
return {
numberOfItems: 0,
items: []
};
},
componentDidMount: function () {
$('#MyContainer .loading').show();
$.get(this.props.source, function (result) {
var response = result.response;
this.setState({
numberOfItems: response.list.numberOfItems,
items: response.list
});
}.bind(this))
.done(function () {
$('#MyContainer.loading').hide();
});
},
render: function() {
return(
//Stuff here
)
};
ReactDOM.render(
<RecommendationsList source="/my/api/call/here"/>,
document.getElementById('MyContainer')
);
Answer
React is just the view layer. It doesn't concern itself much with fetching data and leaves that up to you. I use jQuery
's AJAX functionality for ease of use but you can really use whatever AJAX library you want.
From the code you have provided, you are doing everything correct. You are waiting for the component to mount componentDidMount
.
One note to say about keeping asynchronous JavaScript clean, with multiple callbacks; I would assign the call to a variable.
var request = $.get(this.props.source, function (result) {
var response = result.response;
this.setState({
numberOfItems: response.list.numberOfItems,
items: response.list
});
}.bind(this));
Then bind listeners to that variable.
request.done(function () {
$('#MyContainer.loading').hide();
});
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM