npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

react-universal-data

v4.1.2

Published

Easy to use hook for getting data on client and server side with effortless hydration of state

Downloads

73

Readme

🗂 react-universal-data

Easy to use hook for getting data on client and server side with effortless hydration of state

  • [x] Only 600B minified and gziped
  • [x] Simple hooks API
  • [x] TypeScript
  • [x] Can handle updates
  • [x] Simple cache
  • [x] 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 ~~bastard~~ app while SSRing like it's NO BIG DEAL, effortlessly PASS IT to the client and render THE SHIT out of it

@razdvapoka

📦 Install

$ npm i -S react-universal-data
$ yarn add react-universal-data

📖 Docs

useFetchData

Requests data and preserves the result to the state.

type useFetchData<T> = (
  // async function that can return any type of data
  fetcher: (key: string, context: { isServer: boolean }) => Promise<T>,
  // unique key that will be used for storing & hydrating data while SSR
  key: string,
  // use cached value for specified duration of time, by default it will be requested each time
  ttl?: number
) => AsyncState<T>

⚠️ The key must be unique for the whole application.

Returned object can be in 4 different forms – depending on the promise's state.

export type AsyncState<T> =
  // initial
  | { isReady: false; isLoading: false; error: null; result: undefined }
  // fulfilled
  | { isReady: true; isLoading: false; error: null; result: T }
  // pending
  | { isReady: boolean; isLoading: true; error: Error | null; result?: T }
  // rejected
  | { isReady: false; isLoading: false; error: Error; result?: T }
import React from 'react'
import { useFetchData } from 'react-universal-data'

const fetchPost = (id) =>
  fetch(`https://jsonplaceholder.typicode.com/posts/${id}`)
    .then((response) => response.json())

function Post({ id }) {
  const { isReady, isLoading, result, error } = useFetchData(fetchPost, id)

  if (isLoading) {
    return <p>Loading...</p>
  }

  if (error) {
    return <p>Oh no: {error.message}</p>
  }

  // You can depend on `isReady` flag to ensure data loaded correctly
  if (isReady) {
    return (
      <article>
        <h2>{result.title}</h2>
        <p>{result.body}</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.

import React, { useCallback } from 'react'
import { useFetchData } from 'react-universal-data'

function UserPosts({ userId }) {
  const fetchPosts = useCallback(() => (
    fetch(`https://jsonplaceholder.typicode.com/posts?userId=${userId}`)
      .then((response) => response.json())
  ), [userId]) // will pereform update if value changed

  const { result = [] } = useFetchData(fetchPosts, 'user-posts')

  return (
    <ul>
      {result.map((post) => <li key={post.id}>{post.title}</li>)}
    </ul>
  )
}
import React, { useCallback } from 'react'
import { useFetchData } from 'react-universal-data'

function useFetchUserPosts(userId) {
  return useFetchData(
    useCallback(() => (
      fetch(`https://jsonplaceholder.typicode.com/posts?userId=${userId}`)
        .then((response) => response.json())
    ), [userId]),
    'user-posts'
  )
}

function UserPosts({ userId }) {
  const { result = [] } = useFetchUserPosts(userId)

  return (
    <ul>
      {result.map((post) => <li key={post.id}>{post.title}</li>)}
    </ul>
  )
}

getInitialData

Handles useFetchData on server side and gathers results for hydration in the browser.

type getInitialData = (element: JSX.Element) => Promise<[string, any][]>
// server.js
import React from 'react'
import { renderToString } from 'react-dom/server'
import { getInitialData } from 'react-universal-data'
import { App } from './App'

async function server(req, res) {
  const element = <App />

  const data = await getInitialData(element).catch((error) => /* handle error */)
  const html = renderToString(
    <html>
      <body>
        <div id='app'>{element}</div>
        <script
          dangerouslySetInnerHTML={{
            __html: `window._ssr = ${JSON.stringify(data)};`,
          }}
        />
        <script src='/client.js' />
      </body>
    </html>
  )

  res.write('<!DOCTYPE html>')
  res.write(html)
  res.end()
}

hydrateInitialData

Hydrates initial data gathered with getInitialData before rendering the app in the browser.

type hydrateInitialData = (initial: [string, any][]) => void
// client.js
import React from 'react'
import ReactDOM from 'react-dom'
import { hydrateInitialData } from 'react-universal-data'
import { App } from './App'

hydrateInitialData(window._ssr || [])
ReactDOM.hydrate(<App />, document.getElementById('app'))

💻 Demo

Edit react-universal-data-ssr

🔗 Related

Packages

Real world usages


MIT © John Grishin