Skip to content

Instantly share code, notes, and snippets.

@eivindml
Created March 15, 2019 10:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eivindml/bc425e25b284a5dc833ad1d9d4452580 to your computer and use it in GitHub Desktop.
Save eivindml/bc425e25b284a5dc833ad1d9d4452580 to your computer and use it in GitHub Desktop.
const [suggestions, setSuggestions] = useState([])
useEffect(() => {
const query = `*[_type == "suggestion"] {
content, _id, category,
author->{"avatarUrl": image.asset->url, name, _id},
likes[]->{_id, image{..., asset->}},
comments, replied
}`
const subscription = API.listen(query, {}, {events: ['welcome', 'mutation']})
.subscribe(item => {
if (item.type === 'welcome') {
API.fetch(query).then(setSuggestions)
} else if (item.type === 'mutation') {
setSuggestions(s => {
const index = s.findIndex(i => i._id === item.result._id)
return [
...s.slice(0, index),
item.result,
...s.slice(index+1, s.length)
]
})
}
})
return (() => subscription.unsubscribe())
}, [])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment