Pup

v2.x

ModulesunfreezeApolloCacheValue.js

This module is intended for use on the client and aids in "unfreezing" arrays and objects (i.e., making them mutable) passed to functions via the Apollo data cache (where data retrieved from your GraphQL server lives on the client).

For example, in the /ui/components/UserSettings/index.js file, this module is used to unfreeze a user's settings data (an array) so that we can modify it before passing it back to the server for storage.

"Unfreezing" here refers to the Object.freeze() method in JavaScript. This is used internally by Apollo when adding data to its cache. If you directly pass data from the cache to your component as a prop and wish to modify it, you can't. This is because Object.freeze(), like the name implies, literally "freezes" the object from taking on changes (i.e., makes it immutable). This module serves as a reusable workaround for this problem.

Removes unnecessary metadata from Apollo

In addition to unfreezing arrays and objects, unfreezeApolloCacheValue() also removes unnecessary metadata from values like the __typename property which can trip up your GraphQL schema when trying to store your modified copy of the cache data.

Example Usage
// Frozen data from Apollo cache
const dataFromApolloCache = {
  _id: '123',
  title: 'Melt the cubes, man!',
  body: 'Example body. It's early in the morning, leave me be :p',
  __typename: 'Document',
};

dataFromApolloCache.title = 'Blah';
// Results in an error about the object being immutable.

const unfrozenDataFromApolloCache = unfreezeApolloCacheValue(dataFromApolloCache);

unfrozenDataFromApolloCache.title = 'Blah';

// Value of unfrozenDataFromApolloCache
{
  _id: '123',
  title: 'Blah',
  body: 'Example body. It's early in the morning, leave me be :p',
}