Skip to content

Instantly share code, notes, and snippets.

@mtho11
Created January 25, 2020 18:12
Show Gist options
  • Save mtho11/1ab952d2027401163bc0c2e1f86a3c7e to your computer and use it in GitHub Desktop.
Save mtho11/1ab952d2027401163bc0c2e1f86a3c7e to your computer and use it in GitHub Desktop.
React Hook for request
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