【问题标题】:With apollo client, how to trigger resubscription using reactive variables?使用 apollo 客户端,如何使用反应变量触发重新订阅?
【发布时间】:2021-09-04 04:33:26
【问题描述】:

Apollo 客户端和 graphql 版本:

  "dependencies": {
    "@apollo/client": "^3.3.20",
    "graphql": "^15.5.0",
    ...
  }

我想订阅一个由用户输入过滤的列表,在反应中。

使用反应变量来存储用户输入:

import { makeVar } from '@apollo/client'

export const searchVar = makeVar('')

function keyDown(event) {
  if (event.key === 'Enter') {
    searchVar(event.target.value)
  }
}

export default function Search() {
  return (
    <div className="w-full text-black cursor-pointer text-sm flex">
      <input
        type="search"
        name="search"
        onKeyDown={keyDown}
        placeholder="Find"
        className="flex-grow px-4 rounded-lg text-sm focus:outline-none"
      />  
    </div>
  )
}

使用反应变量订阅:

import { gql, useSubscription } from '@apollo/client'
import { searchVar } from './search'

const SUBSCRIPTION = gql`
  subscription Customers($searchStr: String!) {
    customer(
      limit: 10
      where: { name: {_ilike: $searchStr} }
    ) {
      name
      addr
    }
  }
`

export default function customers() {
  const { data, loading, error } = useSubscription(
    SUBSCRIPTION,
    {   
      variables: {
        searchStr: searchVar()
      },  
      shouldResubscribe: true,
    }   
  )
  ...
}

当用户输入内容并按回车时,订阅会被重新订阅,但它不起作用。 我想我以错误的方式使用反应变量或订阅。 https://www.apollographql.com/docs/react/local-state/reactive-variables/

【问题讨论】:

    标签: reactjs apollo-client subscription


    【解决方案1】:

    来自https://www.apollographql.com/docs/react/local-state/reactive-variables/

    Most importantly, modifying a reactive variable triggers an update of every active query that depends on that variable, as well an update of the react state associated with any variable values returned from the useReactiveVar React hook.
    

    使用useReactiveVar,resubscription在reactive变量更新时成功触发。

    【讨论】:

      猜你喜欢
      • 2021-01-23
      • 2019-01-14
      • 2020-08-27
      • 2018-08-25
      • 2019-04-28
      • 2021-05-28
      • 2017-12-25
      • 2017-12-01
      • 2022-12-12
      相关资源
      最近更新 更多