🗂 react-universal-data
Easy to use hook for getting data on client and server side with effortless hydration of state
- Only 600B minified and gziped
- Simple hooks API
- TypeScript
- Can handle updates
- Simple cache
- Suspense on server side via
react-ssr-prepass
💕
This is a NO BULLSHIT hook: just PLUG IT in your components, get ALL THE DATA you need (and some more) both CLIENT- and SERVER-side, HYDRATE that
bastardapp while SSRing like it's NO BIG DEAL, effortlessly PASS IT to the client and render THE SHIT out of it
📦 Install
$ npm i -S react-universal-data
$ yarn add react-universal-data
📖 Docs
useFetchData
Requests data and preserves the result to the state.
⚠️ The
key
must be unique for the whole application.
Returned object can be in 4 different forms – depending on the promise's state.
👀 Fetch a sample post via jsonplaceholder.typicode.com API
const fetchPost = { const isReady isLoading result error = if isLoading return <p>Loading...</p> if error return <p>Oh no: errormessage</p> // You can depend on `isReady` flag to ensure data loaded correctly if isReady return <article> <h2>resulttitle</h2> <p>resultbody</p> </article> return null}
As the hook depends on the fetcher
function identity to be stable, please, wrap it inside useCallback
or define it outside of the render function to prevent infinite updates.
{ const fetchPosts = // will pereform update if value changed const result = } = return <ul> result </ul> }
👀 Create a custom hook for it
{ return } { const result = } = return <ul> result </ul> }
getInitialData
Handles useFetchData
on server side and gathers results for hydration in the browser.
// server.js { const element = <App /> const data = await const html = res res res}
hydrateInitialData
Hydrates initial data gathered with getInitialData
before rendering the app in the browser.
// client.js ReactDOM
💻 Demo
🔗 Related
Packages
react-ssr-prepass
- server-side dependencyya-fetch
- a lightweight wrapper aroundfetch
Real world usages
MIT © John Grishin