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

with-request

v0.0.7

Published

HOC to call cacheable requests

Downloads

3

Readme

withRequest

HOC to call cacheable requests

npm i with-request
yarn add with-request
  1. Params
  2. Examples
  3. Usage with axios
  4. Usage with fetch

Params

createRequest - used to connect with api adapters (fetch, axios) and cancel requests. Returns withRequest HOC

type CreateRequest = (
  params: {
    fetch: () => Promise<any>
    cancel?: () => void
  },
) => WithRequest
  • fetch - called on componentDidMount, componentDidUpdate, available in enhanced component props
type Fetch = (
  params: {
    url: string
    method: string
    headers: HeadersInit
    requestPayload: any
  },
) => Promise<any>
  • cancel - called on componentWillUnmount, componentDidUpdate, available in enhanced component props
type Cancel = (
  params: {
    url: string
    method: string
    headers: HeadersInit
    requestPayload: any
  },
) => void

withRequest

withRequest<Props, Payload, Error = {}, RequestPayload = any, FetchParams = any>({
  url: (props: Props, fetchParams: FetchParams) => string
  headers?: (props: Props) => HeadersInit
  method?: string
  dataKey?: string
  getRequestPayload?: (props: Props, fetchParams: FetchParams) => RequestPayload | null
  callOnProps?: (props: Props, nextProps: Props) => boolean
  callOnMount?: boolean
  cache?: { set: () => void, get = () => null }
  deleteCacheOnUnmount?: () => void
  cancelOnUnmount?: boolean
  cancelOnProps?: (props: Props, nextProps: Props) => boolean
})

default params:

type withRequestParams = {
  method = 'GET',
  headers = () => [],
  dataKey = 'request',
  getRequestPayload = () => null,
  callOnProps = () => false,
  callOnMount = true,
  cache = { set: () => {}, get: () => null },
  deleteCacheOnUnmount = () => {},
  cancelOnUnmount = true,
  cancelOnProps = () => false,
}
  • url - Used to create request url based on component props
type Url<Props, FetchParams> = (
  props: Props,
  fetchParams: FetchParams | null,
) => string
  • method - request method
type Method = string
  • headers - request headers
type Headers = HeadersInit
  • dataKey - prop name when request data should be injected
type DataKey = string
  • getRequestPayload - Used to create request body based on component props
type GetRequestPayload<Props, RequestPayload, FetchParams> = (
  props: Props,
  fetchParams: FetchParams,
) => RequestPayload | null
  • callOnProps - Calls fetch when return true - uses componentDidUpdate to detect updates
type CallOnProps = (props: Props, nextProps: Props) => boolean
  • cache - local cache configuration. set - called after each successful fetch. get - HOC uses returned value from get as payload. Will not call fetch if returns is different than null.
type Cache<Props, Payload, RequestPayload> = {
  set: (
    props: Props,
    requestData: RequestData<RequestPayload>,
    payload: Payload,
  ) => void
  get: (
    props: Props,
    requestData: RequestData<RequestPayload>,
  ) => Payload | null
}
  • deleteCacheOnUnmount - useful to clean cache on unmounting component
type DeleteCacheOnUnmount = () => void
  • cancelOnUnmount - determines if should call cancel on unmount
type cancelOnUnmount = boolean
  • cancelOnProps - calls cancel when return true - uses componentDidUpdate to detect updates
type cancelOnProps = () => boolean

Examples

Basic:

withRequest({ url: () => '//your.api/products' })(YourAwesomeComponent)

Customizable url:

withRequest({ url: ({ id }) => `//your.api/products/${id}` })(
  YourAwesomeComponent,
)

POST with payload:

withRequest({
  url: ({ id }) => `//your.api/products/${id}`,
  method: 'POST',
  getRequestPayload: ({ newProductName }) => ({ name: newProductName }),
})(YourAwesomeComponent)

Call request on props change:

withRequest({
  url: () => '//your.api/products',
  callOnProps: (props, prevProps) => props.page !== prevProps.page,
})(YourAwesomeComponent)

Cache usage example:

const timeCache = (seconds: number) => {
  const duration = 1000 * seconds
  let timer = performance.now()
  let cache = null

  return {
    set: (props, requestData, payload) => {
      cache = payload
    },
    get: (props, requestData) => {
      if (performance.now() - timer >= duration) {
        cache = null
        timer = performance.now()
      }
      return cache
    },
  }
}

withRequest({
  url: () => '//your.api/products',
  cache: timeCache(60),
})(YourAwesomeComponent)

Usage with axios

const withRequest = createRequest({
  fetch: params =>
    axios({
      method: params.method,
      url: params.url,
      data: params.requestPayload,
    }),
})

withRequest({ url: () => '//your.api/products' })(YourAwesomeComponent)

Usage with fetch

const withRequest = createRequest({
  fetch: params => {
    const response =
      params.method === 'GET'
        ? fetch(params.url)
        : fetch(params.url, {
            method: params.method,
            body: JSON.stringify(params.requestPayload),
          })

    return response.then(response => response.json())
  },
})

withRequest({ url: () => '//your.api/products' })(YourAwesomeComponent)