Hello RW community,
I am calling a third party API and in order to do so I am following the instructions in this link.
The API calls works fine, however, I would like to take it one step further.
During the first API call, the api is pulling data about X, Y, Z. The user on the web side of things is interested in X and I show it to the user. Let’s say, after few seconds user is interested in Y as well and I want to show it next to X but I don’t want to make another API call, rather I want to fetch the Y from previous API call. Any tips would be appreciate.
A simple solution would be store info in a database and check the first — like a cache or reservoir.
On the first call over fetch from api. Check if any of x y z exists in db and since not, then save save x y and z to your database.
Then when the ask for something else, check the db cache first and return from db.
You could save a time stamp like fetchedAt and if it is old or stale then get the latest from api and update it and return.
When you say like a cache or reservoir, do I still need to make a database call? If yes, I wanted to minimize the communication with the Internet. Is it advisable to fetch all the x y z to the browser side and show them depending on what the user clicks.
Just consider if you are optimizing too early or prematurely. See Premature Optimization: Root of All Evil or Rationalization? | Scout APM Blog
While I can see reducing third party calls due to api limits rate limits or costs per access (and this storing locally mitigates that) is reducing one call vital at this stage of development? Only you will know the answer but often times it’s not.
Your other option is over fetching (and thus adding a longer response time on the initial call) and caching (and adding cost to that) only to save on a subsequent fetch that may or may not happen— and then you have to build some client side cache and invalidation mechanism.
Is it ultimately needed?
But it sounds like what you’ll need is some client side caching but then you won’t save time as more users do the queries because each of them will need a cache and you won’t save any api calls because each of them will have to prefetch this cache.
Or maybe reconsider your UX if you think globe user isn’t going to be able tk find what they want the first time around?
Depending on the size of the API response(s), I might advocate using
localStorage (see: Web Storage API - Web APIs | MDN)
They are the same idea as @dthyresson’s suggestion of storing in a database/cache/reservoir - but happen in the browser, all client side.
@dthyresson Thanks for the link. I needed to be reminded of this. Also your suggestions totally makes sense.
@bitshift Thanks. The Web Storage API seems intriguing. Let me take a look.
Let me get to coding and see how I can incorporate you two’s suggestions.