useRequest hook & set of components for requesting API data within React applications
npm install react-sadness




useRequest hook & set of components for requesting API data within React applications.
- Built on top of axios
- Supports prerendering
- Provides common components for API needs
- React 16.13 or later
``bash`
npm install axios react react-dom react-sadness
IMPORTANT: You need to install axios, react & react-dom in your project additionally, as they listed as peer dependencies to react-sadness. Installing just react-sadness will not be enough.
First, you need to wrap your app container into the SadnessProvider & mount it into the DOM element (instead of render or hydrate),
`jsx
import React from "react";
import { mount, SadnessProvider } from "react-sadness";
import { BrowserRouter } from "react-router";
mount(
document.getElementById("ui")
);
`
Next, to request data from the API anywhere inside of AppContainer,
`jsx
import I from "immutable";
import React from "react";
import { Response, useRequest } from "react-sadness";
import { toUser } from "../records/User";
const toList = (data) => new I.List(data.map(toUser));
const Users = () => {
const { state } = useRequest("/users", { responseDataConverter: toList });
return (
{(users) => (
{users.map((item) => (
))}
)}
);
};
`
IMPORTANT: Example below illustrates prerendering data with parcel-plugin-prerender plugin.
react-sadness supports prerendering by triggering readyEvent via SadnessReady HoC.
`jsx
import { SadnessReady } from "react-sadness";
const App = () => (
{/ Ready event will trigger after both child requests will done /}
{/ Request projects from API /}
{/ Request talks from API /}
)
`
Afterwards, you need to setup parcel-plugin-prerender to wait before readyEvent, such as,
`json`
"prerender": {
"rendererConfig": {
"renderAfterDocumentEvent": "react-sadness-ready"
}
}
In case if children nodes does not contain any planned API requests, pass force prop to SadnessReady component to force triggering ready event,
`jsx`
const About = () => (
);
Visit react-sadness.vercel.app to browse through react-sadness Storybook.
Or run,
`bash`
make run
to start Storybook server at http://localhost:6006`.