Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

React AJAX

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:

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

<

h1

Data from API

:

h1

     

<

pre

{

JSON.

stringify

(

data

,

null

,

2

)

}

pre

   

div

 

)

;

}

;

export

default

MyComponent

;

Explanation:

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:

  1. 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.

5.

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

<

h1

Data 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.