Next.js Discord

Discord Forum

SWR middleware: Data transformation - any examples?

Unanswered
Barbary Lion posted this in #help-forum
Open in Discord
Barbary LionOP
I want to transform received data within SWR. Is it possible to do data transformation with SWR middlewares? For instance: transform case of property keys, deserialize date values etc.
The only example in that direction is not easy to understand: https://swr.vercel.app/docs/middleware#keep-previous-result

1 Reply

Barbary LionOP
Ok, I've extended the fetcher within a middleware. That worked.

function camelizer(useSWRNext) {
  return (key, fetcher, config) => {
    const extendedFetcher = async (...args) => {
      let { data, ...response } = await fetcher(...args)

      if (data) {
        data = camelcaseKeys(data, { deep: true })
      }

      return {
        data,
        ...response
      }
    }
 
    return useSWRNext(key, fetcher ? extendedFetcher : fetcher, config)
  }
}