从不同的请求字段读取缓存

问题描述 投票:0回答:1

使用 React Native 和 Apollo 客户端,我正在尝试从不同的请求字段正确写入和读取缓存。 我基本上有两种对象类型:“用户”和“事件”,并且我有这些“请求:

所有事件:(事件列表屏幕)

events {
    id
    numberOfParticipants
}

已连接的用户及其注册的事件:(议程屏幕)

me {
    id
    myEvents {
        id
    }
}

用户注册事件的突变:(事件详细信息屏幕)

mutation {
    registerToAnEvent (id: number) {
        event {
            id
            numberOfParticipants
        }
    }

当用户通过调用突变注册事件时:

我已经做了什么: 缓存已更新,事件列表屏幕数据立即受到影响。 (参加人数变化)

我现在想要实现的目标:我想立即通过缓存修改影响议程屏幕。无论出于何种原因,我都必须调用重新获取来更新它。 (当用户注册/取消注册时,事件应该消失或出现在列表中)

这是我的 InMomoryCache 实现的一些代码:

Query: {
  fields: {
    event: {
      read(_, {args, toReference}) {
        return toReference({
          __typename: 'Event',
          id: args.id,
        });
      },
    },
    events: {
      keyArgs: false,
      merge(existing: any[], incoming: any[], allArgs) {
        const events: any[] = existing ? Object.values({...existing}) : [];
        const newEvents = incoming ? incoming : [];
        newEvents.forEach((event: any) => {
          events.push(event);
        });
        return events;
      },
    },
},
User: {
  fields: {
    eventsParticipating: {
      merge(existing: any[], incoming: any[], allArgs) {
        const events: any[] = existing ? Object.values({...existing}) : [];
        const newEvents = incoming ? incoming : [];
        newEvents.forEach((event: any) => {
          events.push(event);
        });
        return events;
      },
    },
},

谢谢您的帮助:)

react-native graphql apollo apollo-client react-apollo
1个回答
1
投票

我成功做到了。实际上我必须使用突变的更新功能,因为对象确实在缓存中被修改,但是返回用户事件列表的查询不会重新执行,因此它保留相同数量的引用。

如果突变返回的事件中的成员列表包含经过身份验证的用户,请将该引用添加到缓存列表中。 (如果您的对象未缓存(即新评论),您可能需要使用 writeFragment)。

否则从数组中删除该引用。

https://www.apollographql.com/docs/react/caching/cache-interaction/

cache.identify() 返回以下形式的结果:

<__tymename>:<id>

参考文献很容易被欺骗,是

{ __ref: <reference> }

此外,modify() 函数采用如下所示的 id:

<__tymename>:<id>
(如果您想定位特定对象)。

我认为最好使用cache.identify()作为modify()的id,但在这种特殊情况下它对我返回未定义。

这是我的代码:

const [
setParticipation,
{data: dataParticipation, loading: loadingParticipation},
] = useMutation(setParticipationMutation, {
    update(cache, result) {
      cache.modify({
        id: 'User:' + user.id,
        fields: {
          eventsParticipating(events = []) {
            const ref = cache.identify(result.data.eventsParticipating);
            if (
              result.data.eventsParticipating.members.filter(
                m => m.id == user.id,
              ).length > 0
            ) {
              return [...events, {__ref: ref}]; // add ref to array
            } else {
              return events.filter(e => e.__ref != ref); // remove ref from array
            }
          },
        },
      });
    },
  });
© www.soinside.com 2019 - 2024. All rights reserved.