Created
January 25, 2020 18:12
-
-
Save mtho11/1ab952d2027401163bc0c2e1f86a3c7e to your computer and use it in GitHub Desktop.
React Hook for request
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 {useState} from 'react'; | |
const useRequestHandler = () => { | |
const [isLoading, setLoading] = useState(false); | |
const [hasError, setError] = useState(false); | |
const [data, setData] = useState(null); | |
const handleRequest = (request) => { | |
setLoading(true); | |
setError(false); | |
return api.get(request) | |
.then(setData) | |
.catch(() => setError(true)) | |
.finally(() => setLoading(false)) | |
}; | |
return {isLoading, hasError, data, handleRequest}; | |
}; | |
const UserList = () => { | |
const {data, isLoading, hasError, handleRequest} = useRequestHandler(); | |
const searchUsers = (value) => handleRequest(`/users?searchKey=${value}`); | |
return ( | |
<React.Fragment> | |
{data.map(u => <p>{u.name}</p>)} | |
</React.Fragment> | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment