react-wrap-request
v7.0.2
Published
A react-hook implementation for the [wrap-request](https://github.com/misantronic/wrap-request).
Downloads
42
Readme
react-wrap-request
A react-hook implementation for the wrap-request.
basic usage
function Component() {
const { $: items } = useWrapRequest(() => fetch(`https://.../`), {
defaultData: [],
deps: [], // fetch will happen when component did mount
});
return <div>{items.map((item) => item.id)}</div>;
}
working with deps
function Component(props) {
const { $: items } = useWrapRequest((id) => fetch(`https://.../${id}`), {
defaultData: [],
deps: [props.id], // whenever props.id update, wrapRequest will re-fetch
});
return <div>{items.map((item) => item.id)}</div>;
}
manual request
function Component(props) {
const wrapRequest = useWrapRequest((id) => fetch(`https://.../${id}`), {
defaultData: [],
});
useEffect(() => {
wrapRequest.request([100]);
}, []);
return <div>{wrapRequest.items.map((item) => item.id)}</div>;
}
transform request
see https://github.com/misantronic/wrap-request#pipe
function Component() {
const items = useWrapRequest(() => fetch(`https://.../`), {
defaultData: [],
deps: [],
}).pipe((items) => items.map((item) => ({ id: item.id })));
console.log('source', items.source);
console.log('transformed result', items.$);
return <div>{items.$.map((item) => item.id)}</div>;
}
pattern matching
function Component(props) {
const wrapRequest = useWrapRequest((id) => fetch(`https://.../${id}`), {
defaultData: [],
deps: [props.id],
});
return wrapRequest.match({
loading: () => <div>Loading</div>,
error: () => <div>Error</div>,
empty: () => <div>No items.</div>,
fetched: (items) => <div>{items.map((item) => item.id)}</div>,
});
}