Skip to content

Possible to support object keys? #166

Closed
@davecoates

Description

@davecoates

Would it be possible to support objects as keys rather than forcing everything to be a string?

In my case I'm looking to do something like

const { data } = useSwr(userDetail.prepare({ id: 5 }));

which returns the same object given the same inputs. The object itself has a method on it that is called by the fetcher:

function fetcher(preparedAction) {
    return preparedAction.call();
}

As it is this doesn't work because the object returned is forced to a string here: https://github.com/zeit/swr/blob/master/src/use-swr.ts#L66

Given the cache is a Map using an object as a key works, eg. changing that line to the following appears to do what I want:

else if (!key || typeof key !== 'object') {
        // convert null to ''
        key = String(key || '');
}

Wrapping it in an array does also work:

const { data } = useSwr([userDetail.prepare({ id: 5 })]);

but the ergonomics aren't as good (especially given if you forget to wrap it in an array it just doesn't work - no errors).

Unfortunately other things assume it's a string as well - eg. CONCURRENT_PROMISES etc are just plain objects rather than a Map.

Is this something that you would be willing to extend the API to accomodate?

My alternative to make this work within the current API constraints would be to have prepare return a string that fetcher can look up into my own global cache... but I was thinking it would be nice to avoid this if swr already did that internally.

Metadata

Metadata

Assignees

No one assigned

    Labels

    discussionDiscussion around current or proposed behaviorfeature requestNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions