Created
October 12, 2021 02:34
-
-
Save foyez/ca969c13eab1203da20cad1967b08bd6 to your computer and use it in GitHub Desktop.
Cancel a api reqest using fetch and axios in React
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 React, {useState, useEffect} from 'react' | |
| const Example = () => { | |
| const [user, setUser] = useState(null) | |
| const signal = axios.CancelToken.source() | |
| useEffect(() => { | |
| (async function loadUser(){ | |
| try { | |
| const {data} = await axios.get('https://randomuser.me/api', { | |
| cancelToken: signal.token | |
| }) | |
| setUser(data) | |
| } catch (err) { | |
| if (axios.isCancel(thrown)) { | |
| console.log('Request canceled', thrown.message); | |
| } else { | |
| // handle error | |
| } | |
| } | |
| })() | |
| return () => signal.cancel('API request is being cancelled') | |
| }, []) | |
| return ( | |
| <div> | |
| <pre>{JSON.stringify(user, null, 2)}</pre> | |
| </div> | |
| ) | |
| } |
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 React, {useState, useEffect} from 'react' | |
| const Example = () => { | |
| const [user, setUser] = useState(null) | |
| const { signal, abort } = new AbortController() | |
| useEffect(() => { | |
| (async function loadUser(){ | |
| try { | |
| const res = await fetch('https://randomuser.me/api', { | |
| method: 'get', | |
| signal | |
| }) | |
| const data = await res.json() | |
| setUser(data) | |
| } catch (err) { | |
| // handle error | |
| } | |
| })() | |
| return () => abort() | |
| }, []) | |
| return ( | |
| <div> | |
| <pre>{JSON.stringify(user, null, 2)}</pre> | |
| </div> | |
| ) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment