I'm tying myself in knots with a React problem which I'm sure can't be as difficult as it seems to me right now.
I'm building a single page app against a RESTful server API that returns resources, together with links that describe what can be done with that resource. And I'm trying to ensure that my client's ajax calls only use URLs retrieved from the server in this way. So, for example, my LoggedInSessionStore contains the URL that allows me to fetch the list of all public documents, say.
The problem I have is how to manage the dependencies between actions and stores. For example, when the action to fetch all public documents fires, it needs to get its URL from the LoggedInSessionStore. But that store may not yet have been populated yet; so the action must not fire until a previous action (fetch the login session) has completed.
So, I want an action that can fetch server data using a URL that is stored in a store. What is the accepted way to ensure that the action cannot fire until that store has been populated?
TL;DR Don't store your URLs in your Stores. Let your actions handle API calls.
In general when using Flux your actions should not know about your stores. Data in a Flux application is meant to flow in one direction:
Components --> Actions --> Dispatcher --> Stores --> Components
Your React components create actions, which are then dispatched by the Dispatcher to your stores. Stores will be notified of the actions via their registered callback and will update themselves accordingly. Components will listen for stores to update themselves and they will update their own state accordingly. Thus the circle is completed.
The point being: Actions should not depend on stores
What I would suggest is that you move all your API logic into actions. This includes the URLs for your API. This is a fairly common pattern in Flux applications:
A component triggers a fetch action on componentDidMount. Displays loading spinner since it does not yet have the data it needs to render.
The fetch action makes an AJAX call to fetch data from the server.
When the data comes back from the server, the action dispatches it as a payload
A store sees the payload and sets its internal state based on the fetched data
The component sees that the store has been updated, and updates its own state accordingly. This causes it to render the app instead of just a loading spinner.
An alternative option is have your fetch logic inside your stores, including the AJAX request code. I find the former easier to reason about (stores know nothing, they just react to data when its available) but it's up to you how you want to implement it. Just make sure that the API fetching logic is in one place only, not split between Actions and Stores.
This thread may also be helpful: Should flux stores, or actions (or both) touch external services?
Related
Imagine a React app where you can list your friends in a sidebar. The site uses Redux to store the state of the friends. In case a user adds a new friend to his list, I have to send a POST to the backend, to save it.
The question is, how should I update the list of friends in the sidebar?
After the post, should I make a GET request and add the response to Redux or should I just use the data and add it directly to Redux, removing the extra GET call?
My suggestion will be doing both. When you are making a request to server update the Redux store which will update your state(Friends list) and will rerender the component.
Also fire the GET request action, so that if there are data that are on the server but not in your redux, that should get retrieved.
(imagine: Using two machine at the same time and adding friends)
And if you are using something similar to a pure component, if your redux store and retrieved data are same, i.e., no new data was available on the server, there will be no change in state and component will not re-render. They will re-render only when there is a difference in state and will display the current list.
IMO both options are valid. However, I like to have a single source of truth in our applications, which is the backend in most cases.
Sometimes, you might even choose to go for both options. This will increase the user experience by preventing a loading state, but if the action fails or the backend data is different than your redux store, it can result in "weird" behavior.
I'm working on a React+Redux application. I'm calling APIs through Redux actions and storing the response data in the Redux state. But there is a case, Where I don't have to store the API response data in the Redux store.
So the question is, Is there any valid reason to call the APIs through
Redux actions or Should I call the APIs directly since I'm not storing
the response data in Redux store?
It depends on what kind of call you're trying to make, and who's concern it is.
Here are a few cases:
Is this a one-way call to track something?. You can fire an action that gets picked up in a middleware. this is a good case for sending analytics.
This doesn't have to be stored in Redux's store.
Is this a call where some other part of your application will need this data?, then this is a good use case for making an update in the Redux Store so other components when read this and use props to decide what to render etc.
Is this a call where it only concerns one component or isolated part?. You can make this call inside the component in componentDidMount since this doesn't concern anyone else
Alternatively take a look at Sagas, they observe all actions that get dispatched and decide what to do with them in a clean way.
The accepted answer quite well explains the scenario where from API call can be initiated. For better user experience, we always show some spinner or busy sign to inform the user that a request is being made and it has not finished yet. It may happen that API response is not mutating the state, but to let the user know some task is going in the background, we usually update store (for global access) or state (for component level access) with value like isFetching or anything meaningful.
So, it depends on the developer, whether he/she want to show some busy sign or silently perform the API request. Moreover, if they want to show busy sign then, they should decide which part of the application should be aware of the API call. If it is restricted to the component level only, then no need to make the call in actions, otherwise, for global level, yes it should be inside action.
For the sake of uniformity, you should always follow the redux way, even though all the responses are not stored in Redux. It is also a question if you are not using the response from an API call why are you making the call. This argument is counter-intuitive. If you are using the response in some way better do it the Redux way. It is advised to always store the response to a call to Redux and use it, I am sure you are making API calls to do some action on UI.
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.
Flux design pattern has been such help in simplifying my web application. However I ended up directly calling web APIs for certain situations simply because Flux seemed such overkill for the job. I was wondering how others might have solved such problem in a Flux way.
As the diagram suggests, we created the Action via the Action Creator for all Web API calls. I will give an example scenario. Let's say there are 3 components that are interested in User Store changes at the moment. User clicks one of them to load a list of user's hobbies from the back-end. But I only want only that one particular UI component to display the list of hobbies due to the user's action. The other 2 components won't change at all. Traditionally this would have been a simple couple lines asynch call with a callback. If you are to religiously follow Flux for this,
You create an action via Action Creator with a specific reference ID
Fetch data via Web API
Upon receiving data, action is created using the Action Creator
User store listens to this result arriving via the action
Update the store
Fire store updated event, all 3 components react to that and check if that was for mine using the reference ID
then finally render with the data fetched in that 1 UI component
My app having many small parts that load data dynamically like this per user action, I decided to use Flux for things that many components have to share states with since the stores act as centralized state provider. How do you guys use Flux to do simple data fetches such as the one mentioned above?
There are couple of ways to solve this.
Let all the components receive the update and the component decide whether to update or ignore the update.
Split up your store and subscribe only to those which are need in the component. This approach can get messy with stores getting dependent on each other and simultaneous dispatch problem.
If you haven't used any flux library , redux is highly recommended. It solves this by allowing the components to subscribe to part of state(store) tree.
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.