mercredi 8 septembre 2021

JavaScript (React.js) - Caching strategies and anti-patterns (DDD)

In my React Native app, I have the following structure:

components/

screens/
   Profile/
      Profile.js
      EditProfile.js

services/
   firebase/
      api/
         users/
            /cache
               usersCache.js

            /helpers

            getUserData.js
            

As you can see, I have a cache of users, which I use to store the data of every single user I fetch.

For example, in getUserData.js, I use the typical memoizing pattern:

 const getUserData = async (userId, cached = true) =>  {
     if(!cached || !usersCache.isUserCached(userId)) {
         const userData = // await ... get user data from backend 
         usersCache.saveUser(userId, userData);
     }

     return usersCache.getCachedUser(userId);
 }

This seems to me an easy use of a cache in order to avoid multiple requests to the server.

In my profile screen, I have a "pull to refresh" system, so I can use the method I have described but with the argument cached equals to false, in order to get not cached data and cache it when retrieved from the server.

Which other kind of things can be done with a cache like this one? (not the device storage)

I mean, I am thinking about (in some parts of my app) using the cache when a request fails, returning the previous cached data. Are there any more strategies?

And, also, a newbie question, in a Domain Driven Design, is it an anti-pattern to update my "API" cache or get its data inside the screens or components? Should it only be accessed inside the api code? Who should have the responsibility?

For example, am I doing bad if in my EditProfile.js screen I do:

 const submitUpdates = async () => {
    // Get the stateful data of my component
    const newUserData = ...
    
    try {
       await api.users.editProfile(newUserData);
       
       ...

       // IS THIS BAD? I AM UPDATING THE CACHE IN THE UI
       usersCache.updateCachedUser(newUserData.id, newUserData);
    } catch(err) {
       ...
    }
     
 }

Aucun commentaire:

Enregistrer un commentaire