Is it possible to update Frontity state automatically when new posts or new comments are published?

Hi!

I’m really enjoying learning Frontity, I think is perfect for people like me who have been working with WordPress and want to learn ReactJS.

I’m going to start a new project and I have been wondering if there is a correct way to update the frontity.state when new posts (or new comments if wp-comments package is installed) are published, so in the frontend the new posts or the new comments appear automatically without the user having to refresh the website from the browser

Actually, when I create a new post or modify an old one on my WordPress site the changes doesn’t appear in frontity.state.source.data and frontity.state.source.post[id] until I refresh the website and I haven’t realised yet how to automatically update the frontity.state when the WordPress endpoints have available new info without having to refresh the page.

Thank you

1 Like

@vitorioalvarovit could you use RxJs hook (useObserverable) and set state? eg https://nils-mehlhorn.de/posts/react-hooks-rxjs

Just like a regular website, which also doesn’t refresh the page the moment you changed something in the backend, you’ll need to build some logic which checks with the server (or this case with the WP REST API) to see if there are any updates and perform an action (like update the page) accordingly.

As far as I know does WP not have an endpoint (REST API, Ajax or even Heartbeat API) which gives data about an update, but that is easy enough to implement in a simple plugin.
Within Frontity all you need to have is a small script which pings that endpoint once in a while (eg. every 5 seconds), and if it returns a value (could be a simple true, or a list of updated object ID’s) you can retrieve the updated content and let React update it.

Not sure if there’s a package for React which can do that automatically, but shouldn’t be too hard to build (or find).

Thank you so much!

I was thinking in doing something like that, using an afterCSR function with setInterval to know if there has been an update in the WP Rest API and if the answer is true:

actions: {
    theme: {
      afterCSR: ({ state, actions }) => {
          setInterval(() => {
            // determine if there is an update between frontiy state and wp rest api info
            // if true do something
          }, 5000);
      },
    },
  },

Making the user know with a message (like “there is a new post or a new comment”) before updating frontity state or doing it automatically with actions.source.fetch(${state.router.link}, { force: true }) if the change is a modification of something already fetched.

1 Like

Were you able to make any progress with this approach? It seems like a logical solution but I’ve had trouble implementing it myself. When I update the state on the server side, I’m still see the original state on the client side.