【问题标题】:How to force refetch the entire node in Relay?如何强制重新获取 Relay 中的整个节点?
【发布时间】:2022-11-02 01:34:44
【问题描述】:

假设我们有这个突变:

const [addCryptoAddress] =
  useMutation(graphql`
    mutation useCrypto_AddCryptoWalletAddressMutation(
      $input: AddCryptoAddressInput!
    ) {
      addCryptoAddress(input: $input) {
        userAccount {
          cryptoCurrencyAddresses {
            count
            edges {
              node {
                id
                address
              }
            }
          }
        }
        errors {
          message
        }
      }
    }
  `);

如果成功,新的CryptoCurrencyAddresses 将在UserAccount 下可用。

现在假设在代码的其他地方我们有一个lazyLoadQuery 来获取这些地址,例如

const { visitor } = useLazyLoadQuery<ManualPayoutMachineContextQuery>(
  graphql`
    query ManualPayoutMachineContextQuery {
      visitor {
        userAccount {
          cryptoCurrencyAddresses {
            edges {
              node {
                id
                address
                canDelete
                currency
                isDefault
                label
              }
            }
          }
        }
      }
    }
  `,
  {}
);

但是,请注意,此查询引用了突变中未提及的其他字段。结果是所有未提及的字段在突变后立即未定义,即

visitor.userAccount?.cryptoCurrencyAddresses.edges
  .map(({ node }) => {
    return {
      address: node.address,
      canDelete: node.canDelete,
      currency: node.currency,
      id: node.id,
      isDefault: node.isDefault,
      label: node.label,
    };
  });

产生:

[
  {
    address: '0xc0ffee254729296a45a3885639AC7E10F9d54979',
    canDelete: undefined,
    currency: undefined,
    id: 'WyJDcnlwdG9DdXJyZW5jeUFkZHJlc3MiLDIwMjE3NF0=',
    isDefault: undefined,
    label: undefined,
  }
]

除了列出突变中的每个重叠字段之外,是否有办法强制依赖此数据的所有查询在检测到新数据时重新加载?

【问题讨论】:

    标签: relayjs relaymodern


    【解决方案1】:

    您可以将fetchPolicy 设置为store-and-network,如下所示:

    const { visitor } = useLazyLoadQuery<ManualPayoutMachineContextQuery>(
      graphql`
        query ManualPayoutMachineContextQuery {
          visitor {
            userAccount {
              cryptoCurrencyAddresses {
                edges {
                  node {
                    id
                    address
                    canDelete
                    currency
                    isDefault
                    label
                  }
                }
              }
            }
          }
        }
      `,
      {},
      {
        fetchPolicy: 'store-and-network',
      }
    );
    

    store-and-network 将使用存储的数据并始终进行网络请求,而无需进行任何处理。

    【讨论】:

      猜你喜欢
      • 2018-12-06
      • 2017-11-27
      • 2018-01-03
      • 2016-04-28
      • 2016-09-24
      • 2017-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多