Skip to content

Instantly share code, notes, and snippets.

@steveholgado
Last active April 29, 2020 20:25
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 steveholgado/c2ba451d0874d651e8f941c87dcaa8ff to your computer and use it in GitHub Desktop.
Save steveholgado/c2ba451d0874d651e8f941c87dcaa8ff to your computer and use it in GitHub Desktop.

React useMostRecentFetch hook

A hook for fetching data where only the response from the most recent fetch request is needed.

When the arguments are updated, a new fetch request is triggered and the previous one is aborted and ignored.

This is useful in situations where a user might make selections in the UI that trigger multiple fetch requests. For example, selecting from a group of filters which then fetches new data from an API. In this situation, only the most recent selection is relevant.

Example usage

const { data, error, loading } = useMostRecentFetch('https://example.com/api', {
  method: 'POST',
  body: JSON.stringify({ filter1: 'value', filter2: 'value' })
})
import { useState, useEffect, useRef } from 'react
function useMostRecentFetch(url, options = {}) {
const abortController = useRef(new AbortController())
const [data, setData] = useState(null)
const [error, setError] = useState(null)
const [loading, setLoading] = useState(false)
useEffect(() => {
abortController.current.abort()
abortController.current = new AbortController()
setLoading(true)
fetch(url, {
...options,
signal: abortController.current.signal
})
.then(res => res.json())
.then(data => {
setLoading(false)
setData(data)
})
.catch(err => {
if (err.name === 'AbortError') {
return
}
setLoading(false)
setError(err.message)
})
}, [url, options])
return { data, error, loading }
}
export default useMostRecentFetch
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment