Making AJAX Requests In React: Difference between revisions
Jump to navigation
Jump to search
(Created page with "Category:ReactCategory:Web Development == Overview == Notes on how to use an AJAX request to fill out the state of a React component. == AJAX libraries == It's nece...") |
No edit summary |
||
| Line 11: | Line 11: | ||
* [https://github.com/visionmedia/superagent superagent] | * [https://github.com/visionmedia/superagent superagent] | ||
* [https://github.com/github/fetch fetch] | * [https://github.com/github/fetch fetch] | ||
== Usage == | |||
An example of how to make an AJAX call to retrieve JSON data using axios. The data retrieved is a JSON object (or list of objects), not a JSON string. | |||
<syntaxhighlight lang="js"> | |||
axios.get("/path/to/content/") | |||
.then(res => { | |||
const data = res.data; | |||
}) | |||
.catch(err => { | |||
console.log("Something went wrong: " + err); | |||
}); | |||
return data; | |||
</syntaxhighlight> | |||
== Notes == | == Notes == | ||
<references /> | <references /> | ||
Latest revision as of 12:35, 18 March 2018
Overview[edit]
Notes on how to use an AJAX request to fill out the state of a React component.
AJAX libraries[edit]
It's necessary to use a library to make AJAX calls. These libraries are independent of React. They are installed with NPM. [1]
- Axios
Apparently Axios is a little more compact than fetch, e.g. with fetch it's necessary to convert AJAX responses to JSON; with Axios that step is automatic. And error handling is supposed to be better with axios.[2] - superagent
- fetch
Usage[edit]
An example of how to make an AJAX call to retrieve JSON data using axios. The data retrieved is a JSON object (or list of objects), not a JSON string.
axios.get("/path/to/content/")
.then(res => {
const data = res.data;
})
.catch(err => {
console.log("Something went wrong: " + err);
});
return data;
Notes[edit]
- ↑ AJAX Requests in React: How and Where to Fetch Data - Dave Ceddia
- ↑ Fetch vs axios.js for making http requests - Medium