Skip to content

Turn minifying function names back on (eventually) #209

@david-crespo

Description

@david-crespo

We have a hack in place in order to make the use of method.name in the useSWR hook work under production minification. This increases the bundle size by 7 or 8%, so we don't want to do this forever.

This is in service of the typing of useApiData. We need a string method name to pass to SWR for caching purposes.

Desired implementation

Ideally we would be able to pass the name directly like this:

// data has type ApiProjectView
const { data } = useApiData('apiProjectsGetProject', { projectName: 'prod-online' })

and then the implementation would be able to pull the corresponding method off the API object like this:

function useApiData(methodName, params) {
  const paramsStr = JSON.stringify(sortObj(params))
  return useSWR([methodName, paramsStr], () => api[methodName](params))
}

The problem is I haven't been able to get the types to work on the above version. It needs to be able to use the method name string to pull the method (and params and response type) out of the api object.

Current implementation

Instead of passing the method name, what I've done is pass the method itself, which is much easier to pull the params and response types out of:

function useApiData<P extends Params, R>(
  method: (p: P) => Promise<R>,
  params: P
) {
  const paramsStr = JSON.stringify(sortObj(params))
  return useSWR<R>([method.name, paramsStr], () => method(params))
}

const { data: project } = useApiData(api.apiProjectsGetProject, {
  projectName: 'prod-online',
})

But this means we're stuck using method.name to get a name for the cache key. We could pass both the method and the method name, but that loses type safety because you could pass a method and method name that don't match, and the types wouldn't catch it. Or at least if we could get the types to catch it, we should be able to pass the method name by itself.

I'm fairly confident there's a way to make this work the right way (passing a string), I just haven't gotten there yet.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions