Last active
April 13, 2023 10:13
-
-
Save lejonmanen/66f2fc1d4630ebf5770be99a7dd249ce to your computer and use it in GitHub Desktop.
Send AJAX request in React component
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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