react-use-load
— Data loading management in React based on React hooks.
useLoad()
is a custom React hook that handles loading and catching errors.
It also have full TypeScript support as it is written in this language.
Example:
import useLoad, { Loading } from 'react-use-load';
const fetchData = fetch('path-to-your-api')
.then(r => r.json());
const DataComponent = () => {
const data = useLoad(fetchData);
if (data === Loading)
return <LoadingSpinner />;
if (data instanceof Error)
return <ErrorPopup error={data} />;
return data...; // render your data!
}
Yes, that's it!
I was personally tired of writing
useState
s anduseEffect
s all the time (as well as writing actions for everything in Redux😕 ). Writing such hook was a logical outcome.
I tried to make a hook that returns a single variable, so you control the name of it.
And data === Loading
or data instanceof Error
can be read so naturaly!
Dependencies
Usually requests have some dependencies. For example, it can be getting user by user id, or getting page data by count & offset.
useLoad()
supports dependencies!
Example:
import useLoad from 'react-use-load';
const UserPopup = ({ userId }) => {
const user = useLoad(() => fetchUser(userId), [ userId ]);
if (user === Loading)
return <LoadingSpinner />;
if (user instanceof Error)
return <ErrorPopup error={user} />;
return user...; // render user data
}
This way each time when userId
is changed, useLoad()
will trigger loader and will set user
back to Loading
.
Basically, you can imagine that useLoad
arguments are the same as in useCallback
.
useLoad()
Stateful Sometimes we need to edit something that we received. For example, we loaded a user and we are making a cabinet that can change user data.
Now try to imagine how much useEffect
and useState
you would need to implement this with useLoad()
. Two?
const loadedUser = useLoad(fetchUser);
const [user, setUser] = useState(null);
useEffect(() => {
if (loadedUser !== Loading && !(loadedUser instanceof Error))
setUser(loadedUser);
}, [ loadedUser ])
Yes, two.
Well, what if I say you that inside useLoad()
there is already the state!
So by doing this you would just create twice more states and effects.
That's why there is useLoadState()
:
const [user, setUser] = useLoadState(fetchUser);
That's not all!
You now can refresh your user by doing setUser(Loading)
.
For example:
import { useLoadState, Loading } from 'react-use-load';
const Component = () => {
const [user, setUser] = useLoadState(fetchUser);
return (
<button onClick={() => setUser(Loading)}>
Refresh
</button>
);
}
Component wrapper (Experimental!)
You can see how we repeat those conditions for loading or errors:
if (user === Loading)
return <LoadingSpinner />;
if (user instanceof Error)
return <ErrorPopup error={user} />;
And, to be honest, we don't really change those for each page. Usually we have the same behaviour through the whole app.
Well, hook can't just return those, so we need to wrap our component.
Example:
import { createLoader } from 'react-use-load';
const withLoader = createLoader(
() => <LoadingSpinner />, // on loading
err => <ErrorPopup error={err} /> // on error
);
const UserPopup = ({ userId }) =>
withLoader(() => fetchUser(userId), [ userId ])(
user => {
return user...; // render user data
}
)
In perspective of components they became much smaller. In case we need to load not only the user data, we can use Promise.all
and load all we want.
This feature is experimental and I see it too complicated for now.
useLoad()
Lite version of Another way to deal with too much if
s is just to ignore errors.
There is still onError
callback if you need it, but hook itself will return just Loading
in this case.
import useLoad from 'react-use-load';
const UserPopup = ({ userId }) => {
const user = useLoadLite(
() => fetchUser(userId),
[ userId ],
err => console.error(err)
);
if (user === Loading)
return <LoadingSpinner />; // in case of error we will stuck here
return user...; // render user data
}
onError
is executed in useEffect
so feel free to run setState
inside.