ladda-js / ladda

JavaScript data fetching layer with caching
https://petercrona.gitbooks.io/ladda/content/
MIT License
112 stars 16 forks source link

Array-based entity fetched from cache parsed as object instead of array #45

Open herrherrmann opened 4 years ago

herrherrmann commented 4 years ago

If the api in a ladda-wrapped call returns an array, only the initial call (that does the actual request) returns the array as expected. Any subsequent call (that's fetching the entity from the cache) will return the array parsed an object instead.

It's surprising that the type changes "on the fly" and ladda should probably return the entities more consistently (ideally the way they came from the backend).

Example

Initial ladda call returns:

[{ id: 'asd', name: 'Banana' }, { id: 'tzu', name: 'Pomegrenade' }]

Second and subsequent ladda calls return:

{ 0: { id: 'asd', name: 'Banana' }, 1: { id: 'tzu', name: 'Pomegrenade' } }

Current workaround

A workaround is to wrap the ladda call in another function that extracts the values from the response if it's an object:

export const getEntitiesAsArray = async (id: string) => {
    const entities = await api.myEntities.getAllForId(id);
    // Because ladda parses arrays as objects when returning from cache, we need to retransform to an array here.
    return typeof entities === 'object' ? Object.values(entities) : entities;
};