React AJAX
To implement AJAX requests in a React application, you can typically use the fetch API or third-party libraries such as axios, jquery, and others to make network requests.
Below are the basic instructions for using these two methods:
Making AJAX Requests with the fetch API
fetch is an API built into the browser for making network requests. The following describes how to use fetch the basic steps for making AJAX requests in React components:
-
Importing fetch - If you are using a modern browser, you usually don't need to import
fetch. However, if you need to support older browsers, you can useunfetchsuch a polyfill. -
Using the useEffect Hook - Use the
useEffectHook to handle side effects, such as making network requests. -
Making the Request - Uses
fetchMake a GET or POST request. -
Handling the Response - Uses
.then()to process the response data. -
Error handling - Uses
.catch()to catch and handle errors. -
Updating State - Uses
useStateHook to store the requested data and update the state after a successful request.
Example
import
React
,
{
useState
,
useEffect
}
from
'react'
;
const
MyComponent
=
(
)
=>
{
const
[
data
,
setData
]
=
useState
(
null
)
;
const
[
loading
,
setLoading
]
=
useState
(
true
)
;
useEffect
(
(
)
=>
{
const
fetchData
=
async
(
)
=>
{
try
{
const
response
=
await fetch
(
'https://api.example.com/data'
)
;
const
result
=
await response.
json
(
)
;
setData
(
result
)
;
setLoading
(
false
)
;
}
catch
(
error
)
{
console.
error
(
'Error fetching data:'
,
error
)
;
}
}
;
fetchData
(
)
;
}
,
[
]
)
;
if
(
loading
)
{
return
<
div
Loading...
div
;
}
return
(
<
div
<
h1Data from API
:
h1
<
pre
{JSON.
stringify
(
data
,
null
,
2
)
}
pre
div
)
;
}
;
export
default
MyComponent
;
Explanation:
-
useState and useEffect: When using
useStateto store the data returned by the AJAX request (data) and loading state (loading), and useuseEffectto execute the AJAX request after the component loads. -
fetch: When using
fetchMake a GET request and useresponse.json()to parse the returned JSON data into a JavaScript object. -
Asynchronous Handling: When using
async/awaitto handle asynchronous operations, ensuring the state is updated after the request completes. -
Error handling: In
fetchUse in the requesttry/catchto catch and handle errors that may occur.
Using axios
axios is a Promise-based HTTP client that works in both browsers and Node.js.
Below are the basic steps for using axios:
-
Installing axios - Install axios via npm or yarn.
npm install axios 2.
Importing axios - Import axios in the component.
3.Making the Request - Use axios to make GET or POST requests.
4.Handling Responses and Errors - Uses .then() and .catch() to handle responses and catch errors.
Updating State - Similar to using fetch , use useState to update the state.
Example
import
React
,
{
useState
,
useEffect
}
from
'react'
;
import
axios from
'axios'
;
const
MyComponent
=
(
)
=>
{
const
[
data
,
setData
]
=
useState
(
null
)
;
const
[
loading
,
setLoading
]
=
useState
(
true
)
;
useEffect
(
(
)
=>
{
const
fetchData
=
async
(
)
=>
{
try
{
const
response
=
await axios.
get
(
'https://api.example.com/data'
)
;
setData
(
response.
data
)
;
setLoading
(
false
)
;
}
catch
(
error
)
{
console.
error
(
'Error fetching data:'
,
error
)
;
}
}
;
fetchData
(
)
;
}
,
[
]
)
;
if
(
loading
)
{
return
<
div
Loading...
div
;
}
return
(
<
div
<
h1Data from API
:
h1
<
pre
{JSON.
stringify
(
data
,
null
,
2
)
}
pre
div
)
;
}
;
export
default
MyComponent
;
Online Testing with jQuery
The following example demonstrates getting the shared description of a Github user's latest gist:
Data in React components can be fetched via Ajax in the componentDidMount method; when data is retrieved from the server, it can be stored in state and then the UI re-rendered using the this.setState method.
When loading data asynchronously, use componentWillUnmount to cancel pending requests before the component unmounts.
React example
class
UserGist
extends
React
.
Component
{
constructor
(
props
)
{
super
(
props
)
;
this
.
state
=
{
username
:
'
'
,
lastGistUrl
:
'
'
}
;
}
componentDidMount
(
)
{
this
.
serverRequest
= $.
get
(
this
.
props
.
source
,
function
(
result
)
{
var
lastGist
=
result
[
0
]
;
this
.
setState
(
{
username
:
lastGist
.
owner
.
login
,
lastGistUrl
:
lastGist
.
html_url
}
)
;
}
.
bind
(
this
)
)
;
}
componentWillUnmount
(
)
{
this
.
serverRequest
.
abort
(
)
;
}
render
(
)
{
return
(
<
div
{
this.
state
.
username
}
The user's latest
Gist
shared URL: <
a
href
=
{
this
.
state
.
lastGistUrl
}
{
this
.
state
.
lastGistUrl
}
a
div
)
;
}
}
const
root
=
ReactDOM
.
createRoot
(
document
.
getElementById
(
"
root
"
)
)
;
root
.
render
(
<
UserGist
source
=
"
https://api.github.com/users/octocat/gists
"
/>
);
Try it »
The above code uses jQuery to complete the Ajax request.