Skip to content

Commit

Permalink
feat: add useAsync hook #17
Browse files Browse the repository at this point in the history
  • Loading branch information
dlcastillop committed Dec 2, 2024
1 parent 8c45bc3 commit 82646a4
Show file tree
Hide file tree
Showing 2 changed files with 89 additions and 0 deletions.
41 changes: 41 additions & 0 deletions snippets/js.code-snippets
Original file line number Diff line number Diff line change
Expand Up @@ -1659,5 +1659,46 @@
"};"
],
"description": "React hook to track the dimensions of the browser window"
},
"useAsync": {
"prefix": "useAsync",
"body": [
"import { useState, useCallback } from 'react';",
"",
"export const useAsync = () => {",
" const [state, setState] = useState({",
" data: null,",
" isLoading: false,",
" error: null,",
" isSuccess: false",
" });",
"",
" const execute = useCallback(async (asyncFunction) => {",
" setState((prev) => ({ ...prev, isLoading: true, error: null }));",
"",
" try {",
" const result = await asyncFunction();",
" setState({",
" data: result,",
" isLoading: false,",
" error: null,",
" isSuccess: true",
" });",
" return result;",
" } catch (error) {",
" setState({",
" data: null,",
" isLoading: false,",
" error: error,",
" isSuccess: false",
" });",
" throw error;",
" }",
" }, []);",
"",
" return { execute, ...state };",
"};"
],
"description": "React hook to handle async operations"
}
}
48 changes: 48 additions & 0 deletions snippets/ts.code-snippets
Original file line number Diff line number Diff line change
Expand Up @@ -1790,5 +1790,53 @@
"};"
],
"description": "React hook to track the dimensions of the browser window"
},
"useAsync": {
"prefix": "useAsync",
"body": [
"import { useState, useCallback } from 'react';",
"",
"interface UseAsyncState<T> {",
" data: T | null;",
" isLoading: boolean;",
" error: Error | null;",
" isSuccess: boolean;",
"}",
"",
"export const useAsync = <T>() => {",
" const [state, setState] = useState<UseAsyncState<T>>({",
" data: null,",
" isLoading: false,",
" error: null,",
" isSuccess: false",
" });",
"",
" const execute = useCallback(async (asyncFunction: () => Promise<T>) => {",
" setState((prev) => ({ ...prev, isLoading: true, error: null }));",
"",
" try {",
" const result = await asyncFunction();",
" setState({",
" data: result,",
" isLoading: false,",
" error: null,",
" isSuccess: true",
" });",
" return result;",
" } catch (error) {",
" setState({",
" data: null,",
" isLoading: false,",
" error: error as Error,",
" isSuccess: false",
" });",
" throw error;",
" }",
" }, []);",
"",
" return { execute, ...state };",
"};"
],
"description": "React hook to handle async operations"
}
}

0 comments on commit 82646a4

Please sign in to comment.