Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Created the useGet hook #103

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/hooks/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,4 @@ export { default as useBoolean } from './useBoolean'
export { default as useGetState } from './useGetState'
export { default as useDebounce } from './useDebounce'
export { default as useResize } from './useResize'
export { default as useGet } from './useGet'
28 changes: 28 additions & 0 deletions packages/hooks/src/useGet.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import React from 'react';

/**
* This hook returns the json response of a request
* @param {RequestInfo | URL} url - The url to fetch the json response.
* @param {RequestInit} options - The options given to the fetch.
* @returns An array with three elements. First element is the response element
* it returns null if either loading or error, Second element is the loading element
* returns true if the fetch promise has not returned anything yet, Third element
* is the error element it doesn't return null if the request returned an error
*/
export default function useGet(url, options) {
const [response, setResponse] = React.useState(null);
const [loading, setLoading] = React.useState(true);
const [error, setError] = React.useState(null);

React.useEffect(() => {
fetch(url, options)
.then(res => res.json())
.then(data => {
setLoading(false)
setResponse(data)
})
.catch(err => setError(err));
}, [options, url])

return [response, loading, error];
}