Comments (12)
Yes. For example you can use SWR+socket.io (generally any subscription pattern) like this:
// fetch-data.js
import { mutate } from 'swr'
let latestData = null
// setup ws and broadcast to all SWRs
socket.on('data', data => {
latestData = data
mutate('/api/data', data, false)
})
export default () => latestData
and your component:
import useSWR from 'swr'
import fetchData from './fetch-data'
function App () {
const { data } = useSWR('/api/data', fetchData)
// ...
}
from swr.
Hello there!
cc @shuding
Any idea why the example with web sockets isn't in the examples? Did I miss something in this issue?
Am looking to add web sockets to an application and dont really know if I should just use normal state, or swr.
Thanks
from swr.
We need to document those use cases and best practices.
from swr.
why did the old Subscription example be deleted? Is it wrong?
from swr.
@hitbear518 oops, it should be a mistake I think. Going to add it again, thank you. 🙏
from swr.
I don’t see the subscriptions on the docs, are there any other recommendations for best practices? For instance, mounting and unmounting subscriptions during component clean ups. I assume the fetcher should be returned by a separate hook? Thanks!
from swr.
Would something like this work?
// create-listener.ts
import { mutate } from 'swr'
import { db } from './db' // Firestore DB
export const createListener = (path: string) => {
let data = null
const unsubscribe = db.doc(path).onSnapshot(doc => {
data = doc.data()
mutate(path, doc.data(), false)
})
return {
latestData: () => data,
unsubscribe,
}
}
And then in a custom hook called useSubscription
:
// use-subscription.ts
import { useRef, useEffect } from 'react'
import { createListener } from './create-listener'
export const useSubscription = (path: string) => {
const unsubscribeRef = useRef(null)
const swr = useSWR(path, path => {
if (unsubscribeRef.current) {
unsubscribeRef.current()
}
const { unsubscribe, latestData } = createListener(path)
unsubscribeRef.current = unsubscribe
return latestData()
})
useEffect(() => {
return () => {
// clean up the subscription if it exists
if (unsubscribeRef.current) {
unsubscribeRef.current()
unsubscribeRef.current = null
}
}
}, [path])
return swr
}
And, finally, in your component:
const { data } = useSubscription('users')
from swr.
I would be very happy to see the official way of working with sockets in docs
from swr.
This is exactly what I was looking for. But won't this call the subscriber multiple times causing many onSnapshot listeners? On blur/focus for example?
from swr.
This is exactly what I was looking for. But won't this call the subscriber multiple times causing many onSnapshot listeners? On blur/focus for example?
If you’re referring to mine, notice that I store the unsubscribe variable in a ref, and call it whenever the function unmounts / the promise revalidates.
If you want to see a full example of swr sockets being used in production, you can see my library https://github.com/nandorojo/swr-firestore. Unfortunately it’s not the most simple code since it covers all things Firestore, so maybe I can add a tutorial at some point.
from swr.
@nandorojo Nope, that was once again exactly what I was looking for! Thanks :)
from swr.
Yes. For example you can use SWR+socket.io (generally any subscription pattern) like this:
// fetch-data.js import { mutate } from 'swr' let latestData = null // setup ws and broadcast to all SWRs socket.on('data', data => { latestData = data mutate('/api/data', data, false) }) export default () => latestDataand your component:
import useSWR from 'swr' import fetchData from './fetch-data' function App () { const { data } = useSWR('/api/data', fetchData) // ... }
How do we replicate something similar without WS?
I see most of the hosting providers are not supporting socket, including Vercel.
I see you are doing something similar to the Vercel page. Can we have an example how do you implement that?
Check my question here: #2337
from swr.
Related Issues (20)
- useSWR not making the fetch request
- useSWR deduped by mistake after cache clear HOT 1
- useSWRInfinite continually fetches the first page (no caching observed) HOT 3
- Type mismatch on SWR Configuration
- Got "None of the selected packages has a "watch" script" when pnpm watch run HOT 2
- useSWR seems to trigger suspense boundaries even if not using suspense mode HOT 5
- Type error when overriding global fetcher function with null HOT 3
- SWR mutate does not trigger even if I have a hook mounted with the same key HOT 1
- fallback doesn't work with `useSWRInfinite` and next app router HOT 1
- Type error when fallback option with undefined.
- Repeat render
- useSWRMutation - Type error: Expected 2-3 arguments, but got 1. HOT 1
- Cannot read properties of null (reading 'useSyncExternalStore') HOT 1
- Optimistic update with useSWRMutation HOT 2
- typescript is incorrect when using different fetchers but the same key HOT 3
- Type safe Key as Url for the SWR fetcher
- Unexpected `revalidateIfStale = false` initial load behavior on key change HOT 1
- useSWR('key', fetcher) calls fetcher non-deterministically even when `key` is in the fallback
- Can I call both of onSuccess function in trigger options and useSWRMutation options?
- Fetcher isn't run again when error boundary resets using Suspense. HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from swr.