How to persist cached data beyond a phone reboot or app closure using Redux Toolkit Query with React Native? - react-native

As the question suggests, I'm trying to figure out how to persist cached data beyond a phone reboot or app closure using React Native with Redux Toolkit Query. I've noticed that the cached data gets wiped in those scenarios. I believe that caching data beyond an app closure or phone reboot is a common practice.
I have thought about simply storing the data in client-side Redux using Redux Persist to get around this issue, without persisting the api slice. As this post indicates, persisting the api slice is a bad idea:
What happens when i use RTK Query with redux-persist?.
Any tips on this would be appreciated! Thank you.

Generally I can only repeat what I already said in the other issue:
I do not recommend doing this. Data from a server should be fresh, and this way it defitely won't be.
That said, we are currently working on SSR integration and that, too, will need similar functionality. So some kind of rehydration mechanism will be integrated, probably in Redux Toolkit 1.7 - but until then you have the choice between not keeping api data cached (again, my recommendation. No user wants to open an app and see data from five weeks ago - rather show them a loading screen!) or restoring it, but potentially ruining cache collection of said data.

Related

Does calling AsyncStorage multiple time in a react native app impacts performance?

I am building a React Native app which requires calling AsyncStorage multiple times in different components.
For example a particular screen can only be opened in web if the user is logged in, which requires checking the local storage.
Callings AsyncStorage every time doesn’t seem like a good idea and might impact performance as the application grows.
Is implementing redux the best option or is there any other way?
Yes, if you rely on saving too many records. You can however optimize it by using redux persist or using in-memory cache.
A good read that helped understand optimization and performance of Async: https://medium.com/#Sendbird/extreme-optimization-of-asyncstorage-in-react-native-b2a1e0107b34

React Native state management (Redux, Context API or Graphql)

After I got into the basics of React Native and developed some components, I did some research on how state management is being organised in larger apps and am trying to find out what I should be focusing on to learn those days. At first it seemed to be obvious to me that I would be using Redux, but it seems a lot of people are happy using GraphQL in a way that makes Redux even obsolete after implementing it. Now there's also the Context API and I'm wondering what you would be choosing today when writing an entire new React Native app that would be interacting with 3rd pty APIs a lot.
Thanks and regards,
Dennis
The answer depends on a lot of different factors. There are some cases where choosing one over the other makes more sense, but ultimately the decision is up to you. Nevertheless, let's look at some scenarios where it might make sense to use each of these options.
Redux
Redux is best suited for applications that need complex state management and a single source of truth. Typically you would wrap your entire application in a Redux provider so that the state of your entire application changes when this store changes. So this is best used when you have state that is used in many different places throughout the app and needs to be available to every component. An example might be that of a game where a player's actions impact everything around them. Here you could dispatch actions to Redux when a player takes damage or levels up to increase enemy difficulty.
Context
Context is (in my opinion) simpler to use than Redux and is useful for sharing state between a group of components. This is not necessarily for the entire app, although it can be and would effectively be a simpler replacement for Redux in that case. Rather, Context is used in situations where you have deeply nested components that need state from a parent several layers up, or for components that aren't nested within eachother but need the same data in order to work together. An example of when to use context would be in designing an image editor. You could have an image component wrapped in a filter component wrapped in a crop component wrapped in a sizing component and not want to pass the props down to each level every time. So you would wrap the top most layer in a provider and have each nested component be a consumer. You could also have a toolbar that can change the sizing, filter, etc. and so they would also be consumers and would call functions passed in by the provider. The rest of your app would have its own state and would not change when this state changes.
GraphQL
This is useful if you need to pull in state from several differnt APIs or backend services and combine this state all at once. This is dependent on either fetching from a preexisting GraphQL API or by setting up your own to pull in data from your other endpoints. Since you said you would be interacting with a lot of different 3rd party APIs, you could set up an Apollo server to retreive data from them, or use a service like AWS AppSync with Lambda if you want a managed GraphQL service. The beauty of GraphQL lies in that you can query for only exactly what your application needs at any given time. So instead of the APIs dictating what data the client can access, it is the client that tells the APIs what it wants, and then GraphQL gets it in an efficient manner. A perfect fit for this style of state management would be a blogging application. Here you need to pull in information on an author, and get all of their posts, and get all of the comments on their posts, and get their user info, and then get how many followers they have, etc. Where each of these pieces of data would normally be served from their own REST endpoint, you would end up making dozens - and in some case hundreds - of requests to your APIs and pulling in a huge amount of unnecessary data. With GraphQL you can declare what you want in the shape that you want it and pull it into your app in a single request. This would save you a lot of trouble in trying to see if your APIs have all returned a certain piece of data yet or not, and so you don't have to write a thousand if/else statements in your components. Only one would be necessary. However, GraphQL tends to be much harder (in my opinion) to setup compared to using Redux and Context. So be prepared that there is a tradeoff here. When people switch from Redux to GraphQL, they usually switch to the Apollo library in order to make use of their local state management and cache systems. These are not technically a part of GraphQL but are rather just nice add-ons that Apollo provides.
So that's just a general overview of the strengths and weaknesses of using each option. Again, which one (or which combination) you end up using really is dependent on your app's requirements. My suggestion is to experiment and find out.

Migrating from Firebase JS SDK (Web) to react-native-firebase for offline storage

I have been using Firebase Web SDK for my react-native app (I am using FIRESTORE to store the data). Up to this point, I have had no problems. It all works smoothly. But now I want to add some kind of offline storage mechanism to my app so that I could still offer some functionality or display some content that was cached from the last connected session even if my users are offline. After some investigation, I have the impression that react-native-firebase is the preferred way to go. Now I have some questions and I like to get some advice from the experienced.
Is react-native-firebase the only option to go? I have quickly read about AsyncStorage and it is just a key-value storage. Considering the simplest thing I want to do is page through a list of firestore documents, this kind of storage seems not to be suitable to do this offline. Like If I wanted to do this with AsyncStorage I would have to put all the content (maybe hundreds of documents) I get from the firestore backend, persist them as a single string value, fetch them back, parse them, page them etc. And write custom logic& methods for all these.
If I was to use react-native-firebase, just enabling the offline storage -I assume- takes care of this for you and you don't have to write any custom logic for offline storage usage. I assume the data that has persisted for offline usage has the same structure as it does in firestore database. I feel like If I use anything other than react-native-firebase, I would have to handle all the custom logic for persisting, reading and rendering the data offline myself. Is that right?
The biggest concern I have is the amount of code refactoring that might be required. I have many lines of code and so many .get().then() like lines where I get and render the data from firestore. In the documentation of react-native-firebase it says:
...aims to mirror the official Firebase Web SDK as closely as
possible.
I am not sure to what extent this is true. I have checked the react-native-firebase's firestore module's reference documentation but I just can't tell how many of these querying methods are actually supported.
So, the way to go is react-native-firebase's way? Would it take a heavy toll on me trying to refactor the existing code? Any similar experience do you have?
I would appreciate any help.
Thanks a lot...
Maintainer of the react-native-firebase library here.
...aims to mirror the official Firebase Web SDK as closely as possible.
This is a minor disclaimer as there are some differences between the two, mainly down to how certain things have to be implemented with React Native.
For example, enablePersistence does not exist on RNFB. Instead, persistence is enabled by default and can be toggled off (or on) via settings().
Is react-native-firebase the only option to go? I have quickly read about AsyncStorage and it is just a key-value storage. Considering the simplest thing I want to do is page through a list of firestore documents, this kind of storage seems not to be suitable to do this offline. Like If I wanted to do this with AsyncStorage I would have to put all the content (maybe hundreds of documents) I get from the firestore backend, persist them as a single string value, fetch them back, parse them, page them etc. And write custom logic& methods for all these.
This is technically possible, however there are downsides to this as you have mentioned. With Firestore, when the device goes offline (quite common on apps) and you attempt a read/write it'll read/update your local cache, which will still trigger event listeners. When the app goes back online, it'll automatically re-sync with the server for you.
If I was to use react-native-firebase, just enabling the offline storage -I assume- takes care of this for you and you don't have to write any custom logic for offline storage usage. I assume the data that has persisted for offline usage has the same structure as it does in firestore database. I feel like If I use anything other than react-native-firebase, I would have to handle all the custom logic for persisting, reading and rendering the data offline myself. Is that right?
This is all handled for you. We wrap around the native Firebase SDKs so expect the same level of consistency if you were developing a native Android/iOS app if not using React Native.
The biggest concern I have is the amount of code refactoring that might be required. I have many lines of code and so many .get().then() like lines where I get and render the data from firestore.
Generally everything is the same apart from a few minor methods for reasons mentioned above.
So, the way to go is react-native-firebase's way? Would it take a heavy toll on me trying to refactor the existing code? Any similar experience do you have? I would appreciate any help.
I'd recommend anyone developing with React Native & Firebase to use RNFB. It provides a lot of extra functionality the Web SDK cannot provide with React Native. Apart from a more cumbersome setup & changing imports, it should work very much the same.

manage api calls when using vuex

I am currently working on an asset manager for network/server infrastructure in vue.js.
I am also using vuetify for the look and feel since the goal is to create a progressive web app. Engineers can use their phone to scan tags on company assets to request details.
Currently all data is loaded into the app using a rest api. I am using vuex for state management in the application.
I would like some insights in to when to launch these api requests.
So there is some data i currently load at the start of the web app just after logging in when the main core view is loaded. This is impacting performance. Some examples of loaded data:
-> asset types,vendors,suppliers,...
This data is used in a lot of places in the application. (forms,filters,...)
I prefer not to call the vuex actions to perform the api request form inside a specific component since this could lead to unnecessary request when browsing the app.
The only exception to this being the assets them self since this is a lot of data to load at the start.
The problem i am facing is that on mobile platforms loading the data each time at the start of the app is a waste of data connection. It is possible that the engineer is using the app without actually needing the data.
I know this is kind of an abstract question, i am not looking for the one final awnser. Just some insight or recommendations from the community.
Correct me if I misunderstood but it sounds like you are prefetching a lot of non critical information all at start up. You should really focus on when that data is actually needed and reach out and retrieve it only when its actually needed. A common case of this is on route change, so if you have multiple pages within your app an admin page is likely going to need data that your home screen doesn't need. Wait until you navigate to that page before you retrieve information specific to that page. This is commonly done within the beforeRouteEnter router hook or created life cycle hook. Now to build on this, it may take some time to download that new data after a route change - the page could render before all of its necessary data has been made available. You can use a library like Vue-Promised to handle that intermediate state for sections that require data that is still loading. This allows you to let the page render quickly without having to wait on all of its data.
A couple other tips to further optimize things:
If you data that doesn't change often, sometimes it doesn't hurt to persist that data within the browser, either using the Cache-Control http header when making your http calls or by using something like the browsers LocalStorage or one of the hard persistence methods available within the browser. Theres a number of Vuex plugins that make this really easy, ex. vuex-persist. On startup you can load this data from storage which is faster than making a network call, your app will be able to respond faster and you can even go and make that network request in the background to refresh that data after the page has rendered.
If retrieving large sets of data is an issue then you can page the data to retrieve it in smaller chunks and only retrieve additional "pages" fo data when the user needs it. In tables this is commonly done using pagination buttons or infinite scrolling. Theres a number of libraries that do both of these as well, pagination would likely be built into the vuetify libraries table component.

Packing all dynamic data into a single Vuex store

I'm working on a web application which consists of various pages that rely on ajax calls (via AXIOS) for either fetching data from the server or communicating data back to the server. However, the data that is fetched from the server is 99% of times intact during the lifecycle of a session meaning that it will not be changed (i.e. only displayed to user while involving very low update frequency). Moreover, this data, is just pure text including links to contents, formatted as a JSON Object.
I have just found about Vuex, and I have been thinking about packing all these get Ajax requests scattered across different components and centralize them in a Vuex Store in a way that, when the application loads, all required data would be fetched from the server so that no more communication with the server to get such data during the lifecycle of the session would be needed (while only getting the contents such as images, audio, etc via links).
Is Vuex appropriate for this purpose? Is this a good idea at all (based on the concept of speeding up navigations)?
As mentioned in the comments, Vuex is meant to manage complexity and in your case you are planning to fetch 99% of the data at the beginning for your app. So, in client-server aspect, you totally don't need it. Keeping your data structured would be enough.
However, you have also the notion mutation in Vuex. The idea is that you can update the core data only using mutations. In this way, you are protected from unwanted changes and you have a better insight how/in which order your data is changing. So, if you have complex operations on your data (fetched from server and also your apps logic), Vuex would be a good choice.
There are also another interesting features for different kind of apps. Note that is just another trending way to keep your data structured. There are also another strategies but since Vuex is regularly maintained by Vue core team (and it seems to be also in the future), I would suggest it. Especially, if your app keep growing, you will love it more and more. After reading core concepts of Vuex (or better its logic behind Vuex: FLUX), you will have better insight about it.