Simple data fetch in Flux design pattern - reactjs

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.

Related

When I store data in Redux and when not?

I'm working with a react app and currently working with a feature. The main task is showing some charts by getting data from API. And these charts will show the last 30 minutes' data.
I have questions,
In this situation, is it necessary to store these data in the state by Redux, though it can be handled at components very easily? And every time I refresh or request, I get new data (log base data).
When do we make the mind to store data in state and when not?
A redux store is a singleton, thus a single source of truth that can be made available to all components in the whole react application. If your state is intended only for one react component then you don't need a redux store. A useReducer react hook allows to well reproduce the redux pattern in a single component. Stick with a useReducer hook for a single component and use redux library for a store available to an app composed of several components.
Redux is not designed for the specif role of a special type of data.
You can use still store your temporary (30 min) data into redux, and use it to cross your feeling the same as the rest of your data.
But in this case, you might need to reset data after 30 minutes or invalidate your cache, keep your eye in react-query and RTK-query handling these types of actions more easily for you.
If data is being used for many states or those data are being used by many components then you should use redux. You can still go without redux, it is up to you after all.
If you have various components and routes then redux will help you to reduce the codes and also make the codes simpler.
Redux will give the one store for all the components in the project to store and access the data which is better then context or props tricks.
Also if you want to achive something like if user opened two different tabs. Let it be same page or two different pages of your website and if user done an action on page A and you want that page A or page B opened in another tab should get that update then redux can let you achieve that. Context and props passing are not useful in this case.
https://redux.js.org/faq/general#when-should-i-use-redux
Redux is most useful when in cases when:
You have large amounts of application state that are needed in many places in the app
The app state is updated frequently
The logic to update that state may be complex
The app has a medium or large-sized codebase, and might be worked on by many people
You need to see how that state is being updated over time

About calling API in reactjs

I have a question about calling API in react.
Example in the website. We have a lot of page. Each page has a lot of components. And each component has its own data need to get in server.
I see we have two way to call API is:
First. We call all API of each page in a root of each page then set the data to state. After that, we pass data to children Component.
Second. In each component, we call its API to get its data then set the data to component 's state.
So which is better. I need an explain about that.
Thanks you,
There are many ways to pass Data through out the components.
If the application is small and there are small number of child components you can go by making calls in Root folder.
There would be some components that always doesn't render and only rendered based on specific conditions at this point you can go by making calls from that component.
Using redux and redux thunk is always an option if the data is needed in many components and data can be accessed at any point of time.
As noted in the previous answers/comments you could do either one of these. If you plan to use redux it might be easier to chain the api calls in a single action w/ thunk that gets ran on main component load.
Context or Redux would do you well so you don't have to pass tons of data through prop levels.(prop drilling)
I would suggest Redux, IMO context gets too cluttered and by the time you've properly atomized your code to clean up everything you may as well have just went through the overhead of adding redux.
What you should ask yourself is-
Does it make sense to have all this data load at the same time?
Is it appropriate for some api calls to be made from the components that will use them?
You have creative license to do what works best for you.

When I should use a store in ReactJs

I have some questions about the store in ReactJS/Flux implementation.
Basically, I have all my API request which use store. But sometimes, I think store is an overkill features.
A simple example :
I just want display a list of the five last user who have registered on the home of my dashboard. I never want to refresh this list until the user refresh the browser. Should I use a store just for that ?! Or maybe I can create a "global" store for my home page where I include all this little things like this (static display of data requested by the API).
I have another question about store, how much a medium-size application have store ? Because mine have already a lot of store (20-30).
You create one store by page ?! By models ?! By components ?!
Thanks for you response.
TL;DR: many Reducers, one Store.
You tagged this with Redux so I'm going to answer based on the assumption that you're either using Redux or want to use as your Flux implementation.
Regarding the number of Stores, from the Redux docs:
It’s important to note that you’ll only have a single store in a Redux application. When you want to split your data handling logic, you’ll use reducer composition instead of many stores.
So it might be that you want to create a home Reducer to handle all the API responses for your homepage and save those to your single Store.
In your simple example, probably you don't need a store, but I would still use one, as it makes your application scalable. You never know when you would be asked to add new features to it.
About your other question, it totally depends although 20-30 stores sound a bit excessive.
Personally, I use redux and I just have one store with multiple reducers which I combine using redux's combineReducers.
This answer is assuming a few things, but here is my attempt:
A store might be overkill in this case since there is no updating happening after the user refreshes the page. Seems like a static object to me. If you don't have a store already and want to keep going without one I would suggest (assuming you are using flux) to create your dispatcher events within the component that needs this list. The dispatcher will listen for events from your actions. I am guessing your actions make the back-end call to get the last 5 users so the action would then emit an event with the 5 users you are wanting. When the dispatcher receives the event you can set the list of 5 users within your component.
The use case for a store that I have found is when you have "living" objects that change with user interaction on your page. With a store it may be easy to live update your list of 5 users every so often based on an interval and it also serves a way of abstracting out the dispatcher logic from your component into a nice and neat store.

best practices for keep states of page in react-router application

I Have react app which contains many pages. For each page i added store. I using params from url for example photoId then passing to actioncreator which call service and then dispatching data to store. In page component i have store listener. Store imiting change and listener calling render for new state.
Store and action creator relates to this page only. How to create pages more simple?
Thank you!
The Flux model (using actions, dispatcher, and stores) works well for larger apps where a data fetch may affect many components and pages. If you think your app will grow then it may be worth the extra verbosity. If you're keeping your app small then composing plain React components is a great way to keep things simple and there is nothing wrong with doing it as long as you separate the data operations from the display, the way your linked example showed. Have fun!

How do I make multiple Flux apps talk?

I have been creating a React calendar. At first I just wanted to declare the calendar in the html with the appointments, like this:
<Calendar appts={appts} />
But then I realized that my calendar was going to have to be a full app, talking to the REST endpoints and have it's own store and actions.
The calendar was not the end goal, and now I need it to be part of a bigger 'Flux' app. How is everyone architecting their apps, so that the pieces can be reused, say the calendar, in other apps? How do the different Flux apps talk to each other? Are there any examples or blog posts where this is talked about?
Flux is an publisher-subscriber architecture recommendation from Facebook. RefluxJS is an easy to use implementation of this architecture. It adds actions and stores to ReactJS.
Actions are triggers for change. Whenever the user interacts with the page you call an action. Actions have almost completely replaced setState inside a React component for me. When a user creates an event such as a form field change, I fire an action with the event data as a function parameter. In this architecture, actions allow React components (classes) to broadcast publish changes.
Stores subscribe (listen) to actions. The simplest store simply passes on parameters that have changed with a this.trigger call. Other stores may listen to other stores, validate data, stuff parameters into data, set data into an object, or push data onto an array than broadcast the new dataset with a this.trigger call.
React components (classes) and stores can subscribe (listen) to stores. When these stores update, you can
Update state and all dependent props
Do something with the updated store dataset
Reflux comes with a very useful connect mixin which allows you to link the state of a class to a store. Be careful though, be sure to implement getInitialState in the store if you do this. Otherwise, your class will start with a null state. Another useful mixin is the ListenerMixin if you just want the component to do something when a store changes.
For more information, be sure to checkout the RefluxJS README.

Resources