How should I handle ajax requests in a fairly traditional web application? Specifically with using React for views, while having a backend that handles data such as text and
Just in case anybody stumbled upon this and does not know, jQuery makes it super easy to send AJAX calls. Since React is just JavaScript it will work just like any other jQuery AJAX call.
React's own documentation uses jQuery to make the AJAX call so I assume that's good enough for most purposes regardless or stack.
componentDidMount: 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)
});
},
You can use JavaScript Fetch API, it supports GET and POST as well, plus it has building Promises.
fetch('/api/getSomething').then(function() {...})
I would not use JQuery, since AJAX calls is actually not that complex and JQuery is a pretty big dependency. See vanillajs' note on doing AJAX calls without libraries: http://vanilla-js.com/
Kindly checkout the official documentation of Facebook about Complementary Tools
at https://github.com/facebook/react/wiki/Complementary-Tools
They simply recommends few data fetching API's like
My personal favorite would be axios
due to promises which works in browser as well as in nodejs env and even officially reactJS website recommend the same at AJAX and APIs
I definitely proffer you to use Fetch API
. It is very simple to understand, supports all methods and you can use async/await
instead of promise/then
and call back hell.
For example:
fetch(`https://httpbin.org/get`,{
method: `GET`,
headers: {
'authorization': 'BaseAuth W1lcmxsa='
}
}).then((res)=>{
if(res.ok) {
return res.json();
}
}).then((res)=>{
console.log(res); // It is like final answer of XHR or jQuery Ajax
})
In better way or async/await
way:
(async function fetchAsync () {
let data = await (await fetch(`https://httpbin.org/get`,{
method: `GET`,
headers: {
'authorization': 'BaseAuth W1lcmxsa='
}
})).json();
console.log(data);
})();