0

I have an API JSON.

this API changes very often:

  • it can change 10 times in a minute

  • or also 1 time an hour

  • or also 1 time a month.

all things depend on the parameters passed, a few parameters passed are more likely will change.

the problem is I don't know how many times, and I don't want to fetch every millisecond.


so is there any way to fetch it like it is a event listener?

like something like this:

window.addEventListener("APIchange", () => {
    console.log("api changed");
});

so what do I want?

  1. fetch data at the start of the app

  2. wait for changes

  3. if is changes don't fetch (don't consume data)

    • BUT add a button with data changed N times
  4. and if someone clicks the button then fetch the data (so we don't waste internet if user don't want new data, but I want to show to him that it changed N times)

literally something like question on stackoverflow.

enter image description here


here an example of API if you want to: https://api.stackexchange.com/2.3/questions?page=1&pagesize=10&fromdate=1666915200&todate=1667001600&order=desc&sort=activity&tagged=javascript&site=stackoverflow (is the same of StackOverflow, mine is different but is like it)


yes, there is some similar answers here: How to check if JSON is changed in Javascript? but they need everytime to fetch entire data even if not needed. I only need to add the count, create the button and increment the count, on click then fetch, button disappear

stackdeveloper
  • 352
  • 2
  • 21
  • Is this your API? – Konrad Oct 29 '22 at 16:44
  • @KonradLinkowski yes if you want is similar use it, mine is proprietary I can't show it but is literally the same concept of stackoverflow one. – stackdeveloper Oct 29 '22 at 16:45
  • here docs if you need it of StackOverflow one: https://api.stackexchange.com/docs I've pretty done all the other thing but the increment isn't that optimized if I do a setInterval of certain time. – stackdeveloper Oct 29 '22 at 16:48
  • Use websockets or server-side events – Konrad Oct 29 '22 at 16:51
  • @KonradLinkowski what are web sockets? is server side using next.js? I know svelte or react. but don't know sveltekit or next.js. – stackdeveloper Oct 29 '22 at 16:52
  • 1
    [websockets](https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API) and [server-side events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events) – Konrad Oct 29 '22 at 16:52
  • You want your client to subscribe to server-side changes, correct? If it is crucial that a "trace" of changes is available, then your server must store those changes. If you just need to know roughly how many changes has occurred, then you can set up a subscription. Websocket would ideally be your medium, but you could also poll changes every n seconds with normal HTTP. – Jeppe Oct 29 '22 at 17:38

0 Answers0