Subscribe to DB changes in custom React components?

default discord avatar
TheDuncolast year
17

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
    thisisnotchrislast year

    @TheDunco 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
    TheDuncolast year

    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 @thisisnotchris!

  • default discord avatar
    thisisnotchrislast year

    @TheDunco 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
    TheDuncolast year

    Thanks!



    Ah, that makes sense, very cool

  • default discord avatar
    thisisnotchrislast year

    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 help straight from the Payload team with an Enterprise License.