Coder Social home page Coder Social logo

Comments (12)

shuding avatar shuding commented on May 14, 2024 11

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.

itstheandre avatar itstheandre commented on May 14, 2024 6

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.

shuding avatar shuding commented on May 14, 2024 1

We need to document those use cases and best practices.

from swr.

hitbear518 avatar hitbear518 commented on May 14, 2024

why did the old Subscription example be deleted? Is it wrong?

from swr.

shuding avatar shuding commented on May 14, 2024

@hitbear518 oops, it should be a mistake I think. Going to add it again, thank you. 🙏

from swr.

nandorojo avatar nandorojo commented on May 14, 2024

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.

nandorojo avatar nandorojo commented on May 14, 2024

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.

rs-8 avatar rs-8 commented on May 14, 2024

I would be very happy to see the official way of working with sockets in docs

from swr.

RWOverdijk avatar RWOverdijk commented on May 14, 2024

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.

nandorojo avatar nandorojo commented on May 14, 2024

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.

RWOverdijk avatar RWOverdijk commented on May 14, 2024

@nandorojo Nope, that was once again exactly what I was looking for! Thanks :)

from swr.

IlirBajrami avatar IlirBajrami commented on May 14, 2024

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)
  // ...
}

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)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo 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.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.