阿波罗客户端从商店中删除而不会发生突变 [英] apollo client delete from store without mutation

查看:125
本文介绍了阿波罗客户端从商店中删除而不会发生突变的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要通过id从本地存储中删除记录"而不使用突变,因为服务器不支持突变.

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']

这会删除记录,但是当我要求apollo提取项目时,它将进入服务器,就像没有缓存一样.

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.

我只需要更新语言区域

推荐答案

我发现了2种解决方案:

I have found 2 solutions:

查询以下内容:

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
    });

如果您要删除所有地方

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];

这篇关于阿波罗客户端从商店中删除而不会发生突变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆