When should application state update the database? - reactjs

Im currently working on an application which uses react, redux, graphql, apollo and MongoDB.
When the application first loads, im looking to populate the application local data using the database, from there use the application state for any further display to the view. My problem is, im not sure when to make a call to the database given this particular stack

All service call should be done in componentDidMount() life cycle method or you can Use middleware like thunk to call sync service call or db call.
componentDidMount(): After mounting component call service and set state, this state will be used on UI to render any data.
Middleware: You dispatch an action like load products. This will call middle ware to call service and store details in redux store. This can render data on UI.
Let me know if you need more explanation. This is most common architecture which people use for react apps.

Related

Correct way to use redux with async data loading

I'm using redux to load data from the backend in a react application. I'm loading a bunch of data with axios and then I can select one item and see the specific information in a different view. I'm rendering a "Loading" view every time I do a search in the backend. The problem is: this search is fine whenever I load the view refreshing the browser. But when I'm navigating in the own app, I use react-router-dom and I don't need to show the loading screen because it is already in the redux store.
Is there a way to tell redux or react to not make the async call if I already have the data?
Is redux-persist a solution for this? Should I do it manually with a condition in react?
I make the call in the componentDidMount method
You should pass the data from redux store down to your component as a property and you should make a check in componentDidMount or before that if data is empty or null or whatever and make a decision if you should load it after that. You don't need any 3rd party lib for data persistence (like redux-persist) since you actually have it in your redux store already persisted.

Where should I dispatch actions to fetch my data using React-Native and redux

I want to fetch all the data needed to display the dashboard of my app in react-native. The app is similar to the facebook one
I am using react-native, redux, redux-saga, react-navigation and a REST api.
I have to fetch the post list to display the main page and the notification count for the headerBar. The other tabs pages are mounted at the same time as the main one to allow fluid transition. So I need the current user too for the Account page
Finally, the store is persisted and the app can stay in background mode for a long time. So I need to refresh my data often to be sure to have the last changes.
I have sagas which make the call and launch actions to update the store.
Here the strategies I found :
I can connect each page component and give them a fetchAllPageData() which dispatch a fetch action that I call in componentDidMount
I can connect smaller components to allow them to pull the data they need with the same strategy (ie. fetchUser to the component that display the user in the Account Page, fetchNotificationCount to the component that display the number of notifications ...)
I can use create a redux-middleware which listen for page change and call all fetch data actions.
I am currently using a mix of the first and second solutions but I am not very happy with it :
I don't always know where the data are fetched
The strategies which refresh the data once the component is mounted are a bit "hacky" and random
I often have the to move where the call is done when refactoring
What is the state of the art on this subject? What is your recommendation?
The usual recommendation is to intercept actions that make AJAX requests in the middleware and resolve them there before passing the result through.
This article explains it in more depth.
You can / should do in componentDidMount or componentWillMount.

Redux equivalent for Angular2 services

I come from an Angular2 world where there are services that do the normal data loading and so on, now I am on a React, Redux application and am trying to figure out what is the equivalent to Angular2 services in Redux (React). Is it Redux-thunk?
The answer is yes and no.
Yes
Angular services have the logic to load data and normally return a Promise object that gets resolved with data loaded.
With Redux Thunk middleware, you create asynchronous action creators where you put the logic for data loading. But instead of returning a Promise object directly, it waits until the data gets resolved and dispatches an action to update the state with data loaded. React components receive data from Redux store via props. (See connect() method from react-redux.)
No
Angular services are singletons that provides a specific functionality, like $http for facilitating communication with the remote HTTP servers.
Redux Thunk is a middleware and does not do anything but to allow you to write asynchronous action creators that can delay the dispatch of an action, or to dispatch only if a certain condition is met. The action creators are functions that create actions - they are not intended to provide other functionality, like communication with backend servers.
With that said, it is often a matter of coding style where and how you write the logic to load data.
You can use the Fetch API or its polyfill function, or axios library, both are Promise based. You can also consider using Observables, but it is beyond the topic, I think.
As you do with Angular services, you can put all the related logic in a single location and export them. In your action creators, you call these wrapper/helpers, listen for resolution/rejection and dispatch an appropriate action with data resolved as a payload.
Your reducers update the Redux store upon receiving an action dispatched and these state changes are propagated to React components. And this is how the Flux architecture works and how the data flows from Redux Store to React components, AFAIK.
(I might be wrong, please correct me if anything is incorrect and I am open to your opinions. I am still on the way to figure out the best practice to implement services in React applications.)

Setting defaul state in a reactivejs/redux app

In my current ReactJS component, I have to call a REST API and get the JSON. It is done in componentWillMount.
I have introduced Redux in my app. Where should I make the call now to get the JSON and set as the default state? Is it in Redux or my React app?
Any example appreciated.
You'll usually want to dispatch an action from componentDidMount (or Will depending on your lifecycle constraints). That action will kick off the XHR and usually return either a thunk (redux-thunk) or a promise (redux-promise-middleware). If a thunk, it will be set up to dispatch another action with the results, or with a promise it does that for you, then reduce that state in as per normal and bind it to the component.
A common practice is to have a configureStore.js file that exports a configureStore() function that handles the store setup (initial state, middleware, and enhancers) and returns your store. See the "real-world" example in the redux repo for an example of this.
In your case, a simple approach would be to request the data from your REST API when your app starts up, and then when you receive the response, call configureStore(initialState) (where initialState is the data you fetched) and then proceed with the rest of the app setup and initial rendering. This approach will add a little time to your app startup though, because its initialization will be paused while it's waiting for that API response.
Another option would be to just create your store normally (without the prerequisite API fetch), and then make the actual initial state request from your API after your store has been created. When that API response is received, you could dispatch an INITIAL_STATE action, and have reducers ready to handle that. In this approach, you'd probably want some sort of loading indicator in place during this initial fetch, since your app will have rendered or at least started to render during the API request.
If you're doing server rendering, you can just fetch the initial state data from the server side, and attach it to the window object of the index.html that you're rendering. See the "universal" example in the redux repo for an example of this. That'll allow you to simply grab your initial state from the window object when you create your store.

Redux and saving data?

I come from RoR world, and would like to change my application using Redux and React.
React is very simple to understand, you build it up and connect to Redux using web-sockets (Why not just xhr?), Redux accept different actions and respond to React etc.
What I don't understand is, do you save all users in redux store? Or do you use another noSQL to save them? And when I terminate the redux store and start it up again, does my data vanish? I can't find article describing this?
Redux manages state of the client side. Example of what redux handles:
filter in table changed (set state to "loading" and replace table with spinner)
results were loaded (display results in the table)
loading of results failed (show error message)
It does not handle remote communication in itself. I assume that you got the impression that you needs websockets from this tutorial. What happens there is that redux is used on server as well as on client. And websockets are used to make the communication between server and client realtime. The same actions that are executed locally are executed on server and that allows you to propagate them to other clients.
More about AJAX calls and handling asynchronousness in redux:
How to make AJAX request in redux
redux-thunk
redux-saga

Resources