Apollo client and graphql versions:
"dependencies": {
"@apollo/client": "^3.3.20",
"graphql": "^15.5.0",
...
}
I want to subscribe to a list filtered by user input, in react.
Use reactive variable to store the user input:
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>
)
}
Subscription with the reactive variable:
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,
}
)
...
}
The subscription is expected to be resubscribed when users input something and press enter, but it doesn't work. I guess I'm using reactive variables or subscription in a wrong way. https://www.apollographql.com/docs/react/local-state/reactive-variables/