Skip to content

fsyud/swr-min

Repository files navigation

Introduction

implement useSWR from 0

Quick Start

import swr from 'swr-min'

const customFetch = async (...args) => {
  const res = await fetch(...args)
  return await res.json()
}


const Home = () => {
  // useFetch 的第二个参数可以使用自定义的 customFetch
  const [data, isLoading, isError] = swr('api/data', customFetch);
  return ()
}

Dependency Request

// A and B have two parallel requests, and B depends on A's request
const Home = () => {
  const { data: a } = useFetch('/api/a')
  const { data: b } = useFetch(() => `/api/b?id=${a.id}`)
  return ()
}

So how to deal with this kind of demand in the mode of useFetch, when the /api/a interface does not return the result normally, the value of a is undefined, calling a.id in the /api/b interface will directly throw an exception, causing the page Rendering failed.

Does this mean that we can assume that when the interface is called, the url parameter throws an exception, which means that its dependencies are not ready yet, suspend the request for this data; wait until the dependencies are ready, and then initiate a new one for the ready data A round of requests to solve the problem of dependent requests.

Stale-while-revalidate

The core is to allow the client to use stale data in the cache first, and then asynchronously re-validate and update the cache in the background

M8LBGIL

It can be implemented by using ES6's new Map() to record the requested data result in the form of {[key]: [value]}

License

The MIT License.