Packing all dynamic data into a single Vuex store - vue.js

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.

Related

Best practice for fetching data from API periodically and provide it globally (for every Screen)

I'm working on a game-companion app and I was looking for a neat way to fetch data from multiple APIs initiated by starting my app (and maybe also if the user is refreshing the current page with swipe-to-refresh).
The thing is, I planned a dashboard-style homescreen (mostly reduced data from every API), where the user can navigate to different pages (all fed with different API's) and get detailed information for the specific section. I'm not sure how I can provide the API-data 'globally'.
I feel like my main.dart would be way too overloaded, but i can't think of any other way.
What's your thought on that?
Few approaches:
You can use a persistent db and write a wrapper DAO over it that such that anybody with access to this DAO object can write and read from DB. Packages like sqlite help in this regard.
If you are adopting bloc way of state management in your flutter app, then you can create blocs which could be used to share data across your app. flutter_bloc is a good place to start with this.
Via Singleton , If you want a sensitive data that needs to be available within the app globally, then you can create a singleton class that provides read and write from a secure vault. For this secure vault, flutter_secure_storage is convenient or shared_preferences for non sensitive data

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.

Vue: Where to call API?

I currently learning Vue and I am building a movie database app, where users can see movies fetched from an external API and sorted by popular and upcoming.
I have to call different URLs for both categories and I was wondering if I should do that in each component or a separate, third component where all the fetched data is stored?
Does it make sense to use Vuex for a small application like this or is there another best practice? Thanks!
IMHO, Use of Vuex is not about size of application, but the structure. If you want a clean app structure, keep vue SFCs as "simple" as possible. Any logic should be in Vuex and any complex function should be in utility classes.
When you're dealing with an application (not individual components) that utilizes an API, I would recommend placing the API and data hydration into Vuex. (or rather a separate function, but initiated by vuex)
This would allow any component to have access to not only the data, but the loading status of the data. Allowing you (for example) to use something v-if="dataIsLoaded" for components that expect the data to be there, and v-else for loading indicators
There are many resources online and here on stack overflow that will guide you in this. Without knowing how big your application is right now and how big is going to grow, it is difficult to suggest whether to use Vuex or not. In any case, where you make your API calls is / should be independent of your state management.
In general API calls in Vue applications can be made safely in the created lifecycle hook of the component.
created() {}
If you are not going to reuse the data from the API in multiple components, then you can call it in the component where it is needed. If you want to want to do it in a third component, it has to be a kind of wrapper around around your components for popular and upcoming and then pass the data received as a prop to these components.
Approach 1:
MoviesWrapperComponent: Makes the API calls and passes it down to other components
PopularMoviesComponent: Receives data from MoviesWrapperComponent
UpcomingMoviesComponent: Receives data from MoviesWrapperComponent
Approach 2:
PopularMoviesComponent: makes its own API calls.
UpcomingMoviesComponent: Makes its own API calls.
How I do it, is the Ajax calls in each method as in this way it's easier to handle the promisses and the scope of the components.
I'm using the popular Axios plugin, and i'm very happy with it. https://www.npmjs.com/package/vue-axios
I wouldn't use vuex if you just need to share data between a couple of components, but you can use it if you want to learn how to work with vuex.

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.

How inspectlet and other services store user video sessions?

I was wondering how the services like http://www.inspectlet.com/ does store the video sessions. By the looks I don't think it's a webRTC implementation. What i was able to figure out that there is active express socket which is making communication but in that case they will have to store the page and track all the events from DOM. Just wanted to confirm that this is the approach they are following.
Looking at the event listeners on the page, it looks like there are a lot of bindings. For example, the <body> has scroll, keyup, and change events bound to a function. I'm sure it also has mousemove, mouseclick, etc. All of this is likely stored in a Javascript variable (object, probably) and then AJAXed every so often to http://hn.inspectlet.com/adddata with the data parameters. Here is a sample of what is being sent:
http://hn.inspectlet.com/adddata?d=mr,212941,46,337,46,1277)mr,213248,163,498,163,1438)mr,213560,144,567,144,1507)mr,213873,138,240,138,1180)mr,214188,169,184,169,1124)mr,214504,158,520,158,1460)mr,214816,231,487,231,1427)mr,215130,329,197,329,1137)mr,215444,894,289,894,1229)mr,215755,903,295,903,735)s,215755,440,0)&w=259769975&r=494850609&sd=1707&sid=1660474937&pad=3&dn=dn&fadd=false&oid=99731212&lpt=212629
As suggested in Adam's answer, they track many events in the page and send them either via a websocket or post/get request (XHR) to their servers.
I am not sure what inspectlet does specifically, but in general, such a solution will need to follow the below general steps:
When the page is fully loaded (hook on DOMContentLoaded probably) they will send the page data to the server. Then they also hook on MutationObserver in order to track all changes to the DOM in the page, so when something changes dynamically, the tracking script can 'record' it and send it to the server.
The SaaS application in turn, will have a player that will parse all this raw data and then play it back, this will usually require using some virtual file system for assests (images, css, scripts) and handling js scripts to not post back again (replay xhr will have bad results for tracked websites) but play back the mutations as they were captured (recorded)
In regards of data HTML pages compress really well, especially when you can make assumptions about the data (since you know its html) - so yes, they actually cache a lot (similar to what google does in that regards, but google does it for the entire web, not just 'customers')
The DOM Mutations will need to be stored as well. This is up to the algorithm, it can either be stored as plain text or using a smarter data model, storing them in plain text is obviously not the cost effective solution.
The above is an abstraction, there are many edge cases to handle in order to implement such a solution as well as a lot of mathematical and algorithmic thinking in regards of heatmaps to make them accurate.
So after a long search was able to find a new promising solution on the block, which solves all the complex parts in building such service. It is still under development but it solves the problem. Below is the link to it,
https://www.rrweb.io/
https://github.com/rrweb-io/rrweb