Created
March 20, 2019 04:47
-
-
Save uraway/1b6bbe2e71b3feaf3e41428a860f0bf8 to your computer and use it in GitHub Desktop.
React Cancelable Axios
This file contains 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"; | |
import ReactDOM from "react-dom"; | |
import axios from "axios"; | |
function useAxios(fetchAction) { | |
useEffect(() => { | |
const signal = axios.CancelToken.source(); | |
fetchAction({ signal }); | |
return () => { | |
signal.cancel("Api is being canceled"); | |
}; | |
}, []); | |
} | |
function User() { | |
const [result, setResult] = useState(null); | |
useAxios(({ signal }) => { | |
async function getUser() { | |
const res = await axios.get("https://randomuser.me/api/", { | |
cancelToken: signal.token | |
}); | |
setResult(res.data.results[0]); | |
} | |
getUser(); | |
}); | |
return ( | |
<div> | |
{result && ( | |
<p> | |
{result.name.title} {result.name.first} {result.name.last} | |
</p> | |
)} | |
</div> | |
); | |
} | |
function App() { | |
const [mounted, setMounted] = useState(true); | |
return ( | |
<div> | |
<button onClick={() => setMounted(!mounted)}>click</button> | |
<div>{mounted && <User />}</div> | |
</div> | |
); | |
} | |
const rootElement = document.getElementById("root"); | |
ReactDOM.render(<App />, rootElement); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment