阿波罗客户端从商店中删除而没有突变

apollo client delete from store without mutation

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

我试过像这样手动访问商店:

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

这会删除记录,但是当我要求 apollo 获取项目时,它会转到服务器,就像没有缓存一样。

顺便说一下,如果不是删除我只是更新其中一个原始属性,就像这样:

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

然后一切正常,数据更新,apollo继续使用缓存

我知道我应该使用突变,但我不能。

我只需要更新本地

我找到了 2 个解决方案:

查询:

stores {
 products {
  totalCount
  list {
  }
 }
}

**如果您知道确切的变量:**

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