Flux+React.js - Caching API request responses - javascript

I need input from someone experienced with React+Flux+async API requests pattern. What will be the better way to cache api response in the following situation:
I have 3 lists pages of articles each with corresponding API endpoint to fetch data.
each article has details page UI but there's no articleById endpoint, so I just .find necessary article by id in the fetched array
I want to make only 1 request on the list and cache it, so when I go to the details page from the list or return back to the list there will be no API requests.
When I switch to another list I should make the request and cache it.
I'm wondering should I cache the response in WebAPIUtils service which makes actual requests?
Or is it better to hack container component (which is the same for all 3 lists) in a way to know whether it should fire action which starts API request?
Thanks!

Using Stores
You should have ListStore that caches the lists that handles the following action:
LIST_CACHE : this action pushes a List to the List cache.
In your List component, when it receives an update from the ListStore, try to find the List that it's supposed to display and set that in its state.
If the list isn't there, wait for the ListStore to emit a change event, then in the ListStoreChanged handler, try to find the list again.
Now you need to decide on when to make the API request for the list cache. One possible option is making the API request for all the lists when your app loads, and then dispatching all the received Lists to the LIST_CACHE action.
If you haven't already, read this: http://facebook.github.io/flux/docs/overview.html

Related

Is it a bad practice to re-GET list data after a successful item DELETE?

If my client-side application displays a list of items requested from my API, and a user deletes an item, is it best practice to then again call the list GET at the end of the successful HTTP DELETE promise and update the view? Or should the application state simply be updated locally after the delete, without hitting the API again?
I understand optimistically updating your application, but, that is more for view update performance rather than reducing server calls.
You should make another GET request to update the list if the list data may change without user interaction, eg: server-side updates, or another session that can change the same list
With the performance aspect, let the user see the entry deleted ASAP, then very shortly after they will see the updated changes (if there are any), and it won't disturb them.
If there is a deletion error, refresh the updated list regardless
EDIT: I'd also suggest using websockets

Populating an ngrx store with data shared between routes

I have a multi-page form spanning over several routes. All of the routes need the same data shared with them from an API. I can store the response of the API inside ngrx/store and trigger the API call using an effect. My question is more about where to initiate the API call. The API call needs to be made once the user is authenticated, which happens on the very first route I hit (before the first part of the multi page form is visited). The two options I've come up with are:
Triggering the effect inside each route's component meaning I'll just have to request the information every time I visit a route. A guard will prevent all pages being accessible while the user isn't authenticated.
Listen to the authenticated success action inside an effect and make the request to the API there.
I'm sure both are perfectly acceptable and have their trade offs. It'd just be good to get a few opinions!
The second would be the best, requesting the information on demand ergo when the user is authentified and its allowed to use it makes more sense. Inside of the guard, as u said, you should dispatch the action to load the information before you return true/of(true) to signalize that the route can be activated. The naive approach for this would trigger an information request everythime that you try to activate the guarded route.

Retaining a value from a response in node js

On page load, say for a particular route for (e.g. https://localhost:8000/home/index), a service is called and the response from the service is rendered to the page at the client side.
On the same page, I have a link that pops up a Backbone.js modal and from the modal a click event triggers which hits another url (e.g. https://localhost:8000/home/index2) upon which another service call triggers and the response is rendered to another html page.
On the same html page, I want to display a value which I got from the first service call on page load. However, I am unable to retain that value as there are two different requests each time. Hence, I cannot even append the value from first response to the request object and use it a second time.
You can use JavaScripts Web Storage API to storage information on client browser.
MDN Web Storage API
For example, If you are on the first screen and call a service, store the service information on localStorage
localStorage.setItem('firstService', serviceResponseObject);
Once you are navigated to second page, you can use localStorage to read to previous service information
localStorage.getItem('firstService');
There are multiple ways to store state between requests.
From the server, if you're using say Express etc, you could store the result in a Session. Or you can even store state in the requests query params, or from a POST request.
You could also store some data on the client end, using say Cookies or localstorage.
What you choose really depends, it might be best if you explain in more detail what sort of information your passing between pages.
If it's just a simple value, I would go for using query params.
eg. Just place in your url https://localhost:8000/home/index2?value=123, and then from node.js, req.query.value would have your value.

Browser cache and history back button (hashing, history.js)

I have problem with browser back button. Problem exists for IE and google chrome.
I'm creating autoload mechanism for search engine. Mechanism works like google search.
Procedure of building:
1) typing keywords
2) ajax search request
3) response as json
4) building results list using json
5) append list to container
If i have builded results and redirect to another page and back to the page with results, results desapear. I tried a lot solutions described by developers like hashing, history.js and many more but every one is not working.
When you go back, the original HTML of the page is loaded from the cache. Everything you added through Javascript is not stored, so you will have to restore that modification on page load.
For that you can use the popstate event. When that even is fired, you'll need to restore the information. You can do that by re-executing the AJAX request and process the result. Therefore you must save enough information in the url (or hash) to be able to execute the same request again.
That also means, you may need to do earlier requests! For example, if you execute an ajax request to get item X of a list, where X increments each time after the request (so you can get the next item on each click), you will need to make sure that you load all items again. If you don't do that, you will only get the original items on the cached page, and the latest item that was AJAXed, while the items inbetween will be missing.
But if you use pushState or replaceState to store states, you can also store additional data. You can use this to store the JSON result with the state, so you don't need an additional request. Anyway, this is an optimization and is not strictly needed, so you should start with implementing the AJAX request being fired on popstate. You'll need that anyway, because the data may not always be stored with the state, so you will always need the AJAX request as a fallback.

FullCalendar: Fetching the initial date/time-stamp to show once events are fetched from server

First of all, hats off to Adam for pulling off this wonderful, well-written calendar plugin!
Now for a a very typical use case. Below is what I want to achieve:
Fetch events (URL added to eventSources) from the server side as JSON data. This is all fine and I have been able to achieve this. The events get rendered properly.
USE CASE in question: Once the fetch is completed and BEFORE the events are rendered and shown on the browser, I want to 'fetch' the initial month/date to show to the end user. I was thinking of a separate AJAX request to fetch the timing details from the server side and then use 'gotoDate' to switch the view's date.
The reason for this specific requirement, being that that the end user would like to see all the events and initial view w.r.t the server time. In our application it is possible that the client and the server box are not at all sync'd w.r.t time.
Unfortunately, as yet I am not able to locate any callback method that gets invoked once the event fetch (all relevant events) is complete and 'before' the events get rendered on the view.
Any help here will be appreciated. Please let me know if any further info is required.
Thanks,
Mohit
"events" - can process a single event source, this could be an array / JSON feed or function.
"eventSources" - is similar except that it expects multiple event sources, these can also be an array of arrays/functions/JSON feeds (anything that the events option would take).
To process the data before it is rendered I expect you could use a function to do some post processing after you have fetched your data with an AJAX request. See e.g.:
http://arshaw.com/fullcalendar/docs/event_data/events_function/

Categories

Resources