A collection of hooks used for fetching data easily
The new Render-as-You-Fetch pattern for fetching data. This library aims at implementing relay pattern for async APIs.
This is tested on huge project. Everything is stable. but we are improving that. if you have an idea you are so welcome.
- install
- useFetching
- useFetchingCallback
- useFetch
- useFetchCallback
- createResource
- React_Concurrent_Mode
$ yarn add react-concurrent
useFetching give us directly data after api resolve,
import { useFetching } from "react-concurrent";
const app = () => {
const { data, isLoading, error } = useFetching(() =>
fetch("http://example.com"),
);
};
useFetchingCallback doesn't fetching until call refetch
import { useFetchingCallback } from "react-concurrent";
const app = () => {
const { data, isLoading, error, refetch } = useFetchingCallback(() =>
fetch("http://example.com/"),
);
return (
<>
<Button onPress={() => refetch()} title="start fetch" />
{isLoading? 'Is loading ...':data}
</>
);
};
useFetch give us a resource, we need to pass that to useResource for get data
import { useFetch, useResource } from "react-concurrent";
const fetchApi = id => fetch(`http://example.com/${id}`);
const app = () => {
const [id, setId] = useState(1); // fetch is calling again if this state changed
const { resource } = useFetch(fetchApi, id);
return <OtherComponent {...{ resource }} />;
};
const OtherComponent = ({ resource }) => {
const { data, isLoading, error } = useResource(resource);
};
useFetchCallback doesn't call fetch until call refetch
import { useFetchCallback, useResource } from "react-concurrent";
const app = () => {
const { resource, refetch } = useFetchCallback(() =>
fetch("http://example.com/"),
);
return (
<>
<Button onPress={() => refetch} title="start fetch" />
<OtherComponent {...{ resource }} />;
</>
);
};
const OtherComponent = ({ resource }) => {
const { data, isLoading, error } = useResource(resource);
};
import { createResource, useResource } from "react-concurrent";
const resource = createResource(() => fetch("http://example.com"));
// resource.preload(); // fetching before render component
const app = () => {
const { data, isLoading, error } = useResource(resource);
};
As mentioned on react document you could use this
import { createResource } from "react-concurrent";
const resource = createResource(() => fetch("http://example.com"));
const App = () => {
return (
<Suspense fallback={"Is loading ...."}>
<OtherComponent />
</Suspense>
);
};
const OtherComponent = () => {
const data = resource.read();
return "loaded";
};