Simplify your stack and build anything. Or everything.
Build tomorrow’s web with a modern solution you truly own.
Code-based nature means you can build on top of it to power anything.
It’s time to take back your content infrastructure.

Subscribe to DB changes in custom React components?

default discord avatar
thedunco2 years ago
5

Hi all,



I'm wondering if there's a way to somehow subscribe to value updates either from the database or from the api? Essentially I'm trying to make a React component that only shows up if a specific checkbox field in a global is set to

true

. How would I go about doing this? Any ideas?



I can use a useFetch hook to fetch the data from the api, but then there's no way to "revalidate" that without polling which is why somehow I'd like to be able to hook into or subscribe to that value with my own custom React component.

  • default discord avatar
    notchr2 years ago
    @408784184765710337

    This is kind of like what SSE's do, right?

    https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events

    Similar to sockets, where a subscription exists on an event

  • default discord avatar
    thedunco2 years ago

    Mmm, I've never really worked with SSEs or read too much about them, but that seems kinda like what I would need. Is it possible with Payload? Would this be connecting to the Mongo database or the Payload API?



    I think if I learn the API and have time to mess around with it (and it works) this will work for me, thanks

    @1049775120559898725

    !

  • default discord avatar
    notchr2 years ago
    @408784184765710337

    Let me know if you need help! There may be other ways too, but this looks promising



    You'd basically use the EventSource interface on the front end



    const events = new EventSource('http://localhost:3001/events');


    Then in Payload/express, you can send data



    And then you can listen to when the eventSource receives data via a subscription on the frontend



    Very similar to sockets, except a one-way flow



    it also accepts credentials if the eventSource needs to be restricted



    Good luck!!

  • default discord avatar
    thedunco2 years ago

    Thanks!



    Ah, that makes sense, very cool

  • default discord avatar
    notchr2 years ago

    Of course, no prob! Lets play some RL soon 😄



    OH should mention, ESBuild uses event source, but like other interfaces, it comes with its own caveats etc



    https://esbuild.github.io/api/#live-reload-caveats
Star on GitHub

Star

Chat on Discord

Discord

online

Can't find what you're looking for?

Get dedicated engineering support directly from the Payload team.