Apollo客户端和graphql版本:
"dependencies": {
"@apollo/client": "^3.3.20",
"graphql": "^15.5.0",
...
}
我想订阅一个由用户输入过滤的列表,在react中。
使用反应变量存储用户输入:
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,
}
)
...
}
当用户输入内容并按enter键时,订阅将被重新订阅,但它不起作用。我想我使用反应变量或订阅的方式不对。https://www.apollographql.com/docs/react/local-state/reactive-variables/
来源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,在更新反应变量时成功触发重新订阅。