Introduction
use-fetch is data fetching plugin based on fetch plugin.
Why?
- Handle global error
- Handle global error view
- Cache
- Timeout/Abourt
- Zero dependencies
Copyright: This template from: charlyllo
Which applications using fetch-use?
React Compatibility
This package designed for react native but there is no spesific react native dependency you can use on react app. But this package didn't test on react app.
Last Updates
Version: v6.0.0
Error property type changed.
The error property type has been edited. (Won't be string anymore) Now you can access the response object directly when an error occured.
todoError.response or todoError.message
IMPORTANT NOTE: if request failed in catch block response property will be null.
Fetch Provider
Wrap your app.tsx file with FetchProvider
import {FetchProvider} from 'fetch-use';
const BASE_URL = 'https:-jsonplaceholder.typicode.com';
<FetchProvider baseUrl={BASE_URL} globalError={() => { console.log('handle global error');}} errorView={<ErrorView />}>
<HomeScreen />
</FetchProvider>
Global Error Handler
If you define global error this function will work everytime when an error occured.
<FetchProvider
globalError={e => {
console.log('global error');
console.log(e);
}}
{...other props}
}
Custom Error Component
You can show a custom component when an error occured or you can turn off this view.
Use setError from useFetchWrapper when you need to close error view back.
import {FetchProvider, useFetchWrapper} from 'fetch-use'
const ErrorView = () => {
const {setError} = useFetchWrapper()
return (
<SafeAreaView>
<Text>error view</Text>
<Button onPress={() => { setError(false) }} title='Hide' />
</SafeAreaView>
)
}
useFetch hook
This an useFetch hook example you can set headers, useCache option or useErrorView
const {
sendRequest: getTodoRequest,
data: todoData,
error: todoError,
destroy: todoDestroy,
} = useFetch<TodoProps[]>('/todos/1', 'GET', {
headers: {
authorization: 'Bearer jwt',
},
useErrorView: false,
useCache: true
})
We add alias for sendRequest because we'll have more useFetch hook
Now you can call getTodoRequest() whenever you want.
useEffect(() => {
getTodoRequest();
return () => {
todoDestroy();
};
}, []);
--
Get the data
useEffect(() => {
if (!todoData) {
return;
}
console.log(todoData);
}, [todoData]);
--
Get the error
If useErrorView enabled error component will be shown.
useEffect(() => {
if (!todoError) {
return;
}
console.log(todoError.message);
console.log(todoError);
}, [todoError]);
--
Post request hook
const {
sendRequest: getPostRequest,
data: postData,
isLoading: postLoading,
error: postError,
destroy: postDestroy,
} = useFetch<PostProps[]>('/', 'POST', {
headers: {
a: 'b'
},
useErrorView: false,
useCache: true
ttlCache: 60000
})
Send the request
useEffect(() => {
getPostRequest({
body: {name: 'jfla', song: 'good vibes'},
contentType: 'application/json', -application/json | multipart/formdata
params: {id: 20}, -if needed not required
});
}, []);
Get the data
useEffect(() => {
if (!postData) {
return;
}
console.log(postData);
}, [postData]);
useCache
If you set useCache to true your request path will be store as key and response will be store as value
Example
const cache {
products: '{name: 'phone', price: 100},'
users: '{name: 'john', lastname: 'doe'}'
}
Also there is ttlCache option default value is: 300000 (5 minute). After expiration that key will be removed.
timeout - TTL
You can throw timeout error. If you pass timeoutTtl prop. default value is 30000
Example
sendRequest({
...other props
timeoutTtl: {
duration: 30000,
}
})
Also you can pass custom timeout callback function
sendRequest({
...other props
timeoutTtl: {
duration: 30000,
onExpired: () => console.log('on expired func')
}
})
Catch timeout via global error handler
<FetchProvider
...other props
globalError={(error: any) => {
if (error?.response?.name === 'AbortError') {
console.log()
}
>
Properties
useFetch
export const useFetch = <T>(
uri: string
method: 'POST' | 'GET' | 'PUT' | 'PATH' | 'DELETE'
options: {
headers?: Record<string, any>;
useErrorView?: boolean; -true
useCache?: boolean; -false
ttlCache?: number; -300000
useLogs?: boolean; -false
}
</FetchProvider>
send request
const sendRequest = async (props?: {
uri: string
params?: Record<string, any>;
contentType?: 'application/json' | 'multipart/formdata'
Example
You can find the example here.