Skip to content

Instantly share code, notes, and snippets.

@lejonmanen
Last active April 13, 2023 10:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lejonmanen/66f2fc1d4630ebf5770be99a7dd249ce to your computer and use it in GitHub Desktop.
Save lejonmanen/66f2fc1d4630ebf5770be99a7dd249ce to your computer and use it in GitHub Desktop.
Send AJAX request in React component
import { useState, useEffect } from 'react'
// This function can be in a separate file
async function getData(setData) {
const url = 'API url here'
const response = await fetch(url)
const data = await response.json()
setData(data)
}
// A component that fetches data from an API and displays it.
const AjaxOnMount = () => {
const [data, setData] = useState(null)
// Fetch data on mount is a side effect, must use useEffect
useEffect(() => {
getData(setData)
// Remember the array [] so that getData will only run when the component is mounted
}, [])
// Use conditional rendering to display "No data" until the data arrives from the API
return (
<section>
<p>{data ? data.message : 'No data'}</p>
</section>
)
}
const AjaxOnClick = () => {
const [data, setData] = useState(null)
// When the user initiates effects, we don't need useEffect
const handleUpdate = () => getData(setData)
// Use conditional rendering to display "No data" until the data arrives from the API
return (
<section>
<p>{data ? data.message : 'No data'}</p>
<button onClick={handleUpdate}> Get data </button>
</section>
)
}
export default AjaxOnMount
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment