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

@scaleway/use-dataloader

v5.1.0

Published

A small hook to handle api requests

Downloads

8,393

Readme

@scaleway/use-dataloader

Tiny hooks to help you manage asynchronous tasks

  • Lightweight
  • Easy to use
  • Easy to integrate with Axios, fetch, or any Promise-based tool

Install

$ pnpm add @scaleway/use-dataloader

How to use

Add DataLoaderProvider to your app

Firstly you need to put the context at the top of your App.

import { DataLoaderProvider } from '@scaleway-lib/use-dataloader'
import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'

ReactDOM.render(
  <React.StrictMode>
    <DataLoaderProvider>
      <App />
    </DataLoaderProvider>
  </React.StrictMode>,
  document.getElementById('root'),
)

Now you can use useDataLoader and useDataLoaderContext in your App

cacheKeyPrefix

You can specify a global cacheKeyPrefix which will be inserted before each cache key

This can be useful if you have a global context (eg: if you can switch account in your app, ...)

import { DataLoaderProvider, useDataLoader } from '@scaleway-lib/use-dataloader'
import React from 'react'
import ReactDOM from 'react-dom'

const App = () => {
  useDataLoader('cache-key', () => 'response') // Real key will be prefixed-cache-key

  return null
}

ReactDOM.render(
  <React.StrictMode>
    <DataLoaderProvider onError={globalOnError} cacheKeyPrefix="prefixed">
      <App />
    </DataLoaderProvider>
  </React.StrictMode>,
  document.getElementById('root'),
)

maxConcurrentRequests

You can specify a maxConcurrentRequests which will prevent DataLoader to launch request simultaneously and wait some to finish before start next ones.

This can be useful if you want to limit the number of concurrent requests.

onError(err: Error): void | Promise<void>

This is a global onError handler. It will be overriden if you specify one in useDataLoader

import { DataLoaderProvider, useDataLoader } from '@scaleway-lib/use-dataloader'
import React from 'react'
import ReactDOM from 'react-dom'

const failingPromise = async () => {
  throw new Error('error')
}

const App = () => {
  useDataLoader('local-error', failingPromise, {
    onError: error => {
      console.log(`local onError: ${error}`)
    },
  })

  useDataLoader('error', failingPromise)

  return null
}

const globalOnError = error => {
  console.log(`global onError: ${error}`)
}

ReactDOM.render(
  <React.StrictMode>
    <DataLoaderProvider onError={globalOnError}>
      <App />
    </DataLoaderProvider>
  </React.StrictMode>,
  document.getElementById('root'),
)

useDataLoader

import { useDataLoader } from '@scaleway-lib/use-dataloader'

const fakePromise = () =>
  new Promise(resolve => setTimeout(resolve('test'), 1000))

function MyComponent() {
  // Use a key if you want to persist data in the DataLoaderProvider cache
  const { data, isLoading, isSuccess, isError, error } = useDataLoader(
    'cache-key',
    fakePromise,
  )

  // This is the first time we load the data
  if (isLoading && !data) {
    return <div>Loading...</div>
  }

  // This happen when you already load the data but want to reload it
  if (isLoading && data) {
    return <div>Reloading...</div>
  }

  // Will be true when the promise is resolved
  if (isSuccess) {
    // Will display "test" in the the div
    return <div>{data}</div>
  }

  // Will be false when the promise is rejected
  if (isError) {
    // Will display the error in the the div
    return <div>{error}</div>
  }
}

export default MyComponent

useDataLoaderContext

import { useDataLoaderContext } from '@scaleway-lib/use-dataloader'

const fakePromise = () =>
  new Promise(resolve => {
    setTimeout(resolve('test'), 1000):
  })


function MyComponentThatUseDataLoader({key}) {
  // Use a key if you want to persist data in the DataLoaderProvider cache
  const { data, isLoading, isSuccess, isError, error } = useDataLoader(
    key,
    fakePromise,
  )

  // Will be true during the promise
  if (isLoading) {
    return <div>Loading...</div>
  }

  // Will be true when the promise is resolved
  if (isSuccess) {
    // Will display "test" in the the div
    return <div>{data}</div>
  }

  // Will be false when the promise is rejected
  if (isError) {
    // Will display the error in the the div
    return <div>{error}</div>
  }
}


function MyComponent() {
  const { reloadAll, reload } = useDataLoaderContext();

  const handleReload = (keyToReload) => () => {
      await reload(keyToReload) // Execute the method
    }
  }

  const handleReloadAll = () => {
      await reloadAll()
    }
  }

  return (
    <div>
      <MyComponentThatUseDataLoader key="test" />
      <MyComponentThatUseDataLoader key="test-2" />
      <button onClick={handleReload("test")}>Reload first</button>
      <button onClick={handleReload("test-2")}>Reload second</button>
      <button onClick={handleReloadAll}>Reload all</button>
    </div>
  )
}

export default MyComponent

API

useDataLoader

const useDataLoader = (
  key, // A key to save the data fetched in a local cache
  method, // A method that return a promise (ex: () => new Promise((resolve) => setTimeout(resolve, 2000))
  {
    onSuccess, // Callback when a request success
    onError, // Callback when a error is occured
    initialData, // Initial data if no one is present in the cache before the request
    pollingInterval, // Relaunch the request after the last success
    needPolling = true, // If true or function return true it will execute the polling
    enabled = true, // Launch request automatically
    keepPreviousData = true, // Do we need to keep the previous data after reload
    dataLifetime, // Max time before previous success data is outdated (in millisecond). By default refetch on every mount
  } = {},
)

| Property | Description | | :----------: | :------------------------------------------------------------------------------------------------------------------------------------------: | | isIdle | true if the request is not launched | | isLoading | true if the request is launched or enabled is true and isIdle is true | | isSuccess | trueif the request finished successfully | | isError | true if the request throw an error | | isPolling | true if the request if enabled is true, pollingInterval is defined and the status is isLoading,isSuccess or during the first fetch | | previousData | if keepPreviousData is true it return the last data fetched | | data | return the initialData if no data is fetched or not present in the cache otherwise return the data fetched | | error | return the error occured during the request | | reload | allow you to reload the data (it doesn't clear the actual data) |