Skip to content

Instantly share code, notes, and snippets.

@sakilahmmad71
Last active July 25, 2021 20:28
Show Gist options
  • Select an option

  • Save sakilahmmad71/aa68eebabd4454b2b1d4f664fb9f20ac to your computer and use it in GitHub Desktop.

Select an option

Save sakilahmmad71/aa68eebabd4454b2b1d4f664fb9f20ac to your computer and use it in GitHub Desktop.
import axios, { CancelTokenSource } from 'axios';
import { useState, useEffect } from 'react';
import { PostInterface, defaultPostInterface } from './models/postInterface';
const App = () => {
/*
const [getVariableName, setValueVariableFunction] : [getVariableName_type, (setValueVariableFunction: setValueVariableFunction_type) => setValueVariableFunction_return_type] = useState<variable_type>(variableDefaultValue);
*/
const [posts, setPosts]: [PostInterface[], (posts: PostInterface[]) => void] = useState(defaultPostInterface);
const [loading, toggleLoading]: [boolean, (loading: boolean) => void] = useState<boolean>(true);
const [error, toggleError]: [string, (error: string) => void] = useState<string>('');
const cancelToken = axios.CancelToken;
const [cancelTokenSource, setCancelTokenSource]: [CancelTokenSource, (cancelTokenSource: CancelTokenSource) => void] = useState(cancelToken.source());
const handleRequestTokenCancellation = () => {
if (cancelTokenSource) {
cancelTokenSource.cancel("User cancelled request operation.");
}
}
useEffect(() => {
axios
.get<PostInterface[]>(`https://jsonplaceholder.typicode.com/posts`,
{
headers: { "Content-Type": "application/json" },
cancelToken: cancelTokenSource.token,
timeout: 5000,
timeoutErrorMessage: "Request time out, please try again."
})
.then((response) => {
setPosts(response.data);
toggleLoading(false);
})
.catch((error) => {
const err: string = axios.isCancel(error) ? error.message : error.code === "ECONNABORTED" ? error.message : error.response.status === 404 ? "Resource not found." : "An unexpected error has occurred";
toggleError(err);
toggleLoading(false);
})
.finally(() => {
console.log("API called with given configurations.");
});
}, []);
return (
<>
<div className="App">
{loading && <button onClick={handleRequestTokenCancellation}>Cancel request</button>}
<ul className="posts">
{posts.map((post) => (
<li key={post.id}>
<h3>{post.title}</h3>
<p>{post.body}</p>
</li>
))}
</ul>
{error && <p className="error">{error}</p>}
</div>
</>
)
}
export default App;
export interface PostInterface {
id: number;
userId?: number;
title: string;
body: string;
};
export const defaultPostInterface: PostInterface[] = [];
@sakilahmmad71
Copy link
Author

axios make request, request timeout and token cancellation example with typescript and react,

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment