apollo client delete from store without mutation

痞子三分冷 提交于 2019-12-11 02:44:26

问题


I need to remove a "record" from the local store by id without using mutation because the server does not support mutations.

I have tried to access manually the store like that:

delete this.apolloClient.store.getState().apollo.data['1112']

this removes the record but when I ask apollo to fetch the items it goes to the server, like there is no cache.

by the way, if instead of removing I just update one of the primitive properties like that :

this.apolloClient.store.getState().apollo.data['1112'].name = 'XXX'

then everything is OK, the data is updated and apollo keep using the cache

I understand that I am supposed to use mutations but I can not.

I need to update only localy


回答1:


I have found 2 solutions:

for a query of:

stores {
 products {
  totalCount
  list {
  }
 }
}

**if you know the exact variables: **

const query = gql(query);
    const data = apolloClient.readQuery({ query, variables:{limit:100, offset: 0} });

    let removedProduct = _.remove(data.stores.products.list, function(product: IProduct) { return product.id === productId; })
    data.stores.products.totalCount = data.stores.products.list.length;

    apolloClient.writeQuery({
        query,
        variables:{limit:100, offset: 0},
        data: data
    });

if you want to remove everywhere

let dataStore = apolloClient.store.getState().apollo.data;
    let productsStore = dataStore[dataStore['ROOT_QUERY'].stores.id];
    let product = dataStore[productId];

    //remove product from cache index
    Object.keys(productsStore)
        .map((key: any) => dataStore[productsStore[key].id])
        .forEach((products: any) => {
            _.remove(products.list, (product) => product.id === productId);
            products.totalCount = products.list.length;
        });

    //remove product's complex fields (array/objects) from cache
    Object.keys(product).map((key: any) => {
        if (Array.isArray(product[key])) {
            return product[key].map((item) => item.id);
        } else if (typeof product[key] === 'object') {
            return product[key].id;
        }
        return null;
    }).forEach((productField) => {
        if (Array.isArray(productField)) {
            productField.forEach((key) => delete dataStore[key]);
        } else if (productField) {
            delete dataStore[productField];
        }
    });

    //remove product from cache
    delete dataStore[productId];


来源:https://stackoverflow.com/questions/45533730/apollo-client-delete-from-store-without-mutation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!