Flux Handling Action State - reactjs

When i am correct in flux there are 2 different kinds of state
Application State (in Stores)
View State (in the Component)
i am trying to build a CRUD application using flux and don't understand what's the smartest way to deal with action state.
consider i've a page with 2 components that are responsible for creating a blogpost. so a editor could choose if the want to use component1 or component2 to create the blogpost.
by pressing on the save button on component1 the component is sending an BLOGPOST_CREATE_ACTION.
In the component i want to display the lifecycle of the action:
Sending blogpost to the server
Blogpost is saved or saving failed
The store can keep track of these states and can emit when it changes.
But as i've 2 different components looking at the same store, the state change would take effect on both of my components.
Flux is build for keeping everything consistent, but in this case i want to get status (including error) informations independent for every component.
How do you deal with such "issues"?

Related

React passing state between instances of the same Component

I'm fairly new to React, and I was trying to create an app that functioned thusly:
The app consists of several Pages, with multiple Components on each Page.
One of these Components is stats, which can change as the user interacts with Components on the Page.
When a user clicks on a certain Component, they will be taken to a "different" page, which is really just another Page, with different text, data, etc. This is carried out through the browserHistory.push() method. I would like to be able to carry over the changed 'stats' component from one Page to the next, but I am not sure how to do so. Furthermore, since I set the default value for stats in the Page component, it seems that any attempt at passing the changed values into the new Page would result in the new values being overridden. Can anyone help me?
Thanks.
State should live above the level of all components that need access to that state.
Remember that one of the principles of React is "one-way" data flow down the component hierarchy. Essentially, data/state should live at a high level, getting passed down to child components and consumed as needed.
In your case, you have some "stats" data that needs to be displayed across multiple Pages. So, "stats" needs to be owned by a component above all of your Page components - perhaps at the root component of the app itself. Pages themselves would just take the data in and render it, potentially with some callbacks appropriate for editing the data.
Read a bit more about Facebook's philosophy for React in "Thinking in React" in the official docs: https://facebook.github.io/react/docs/thinking-in-react.html#step-4-identify-where-your-state-should-live
One option to consider is to use React Redux to store the state of your application. You would then use mapStateToProps (See Redux API for details) to map the state into props for your stats component.

SPA + back button + form state

I am converting a jsp multi-page app(mpa) into a React single-page app (spa). In the mpa, the back button worked and the form retained its state.
In my new React app, the back button works but the form does not retain its state.
Question: is there a trick to make my form retain its state after "backing" to it (in an spa).
Here are the two solutions I came up with:
Encode the entire form state into the url. Then update the browser history with an updated url every time the form changes. But, this seems like a huge pain in the butt.
Modify the structure of my app such that the form in question (a React Component) stays mounted (and just use the css visibility or display property to show and hide). But, in a large app, leaving every page mounted in the DOM seems like it might lead to performance problems.
By the way, I am using popstate and the browser history api to achieve SPA behavior (i.e. i have rolled my own router) as described here.
Hopefully someone can propose a solution that is better than my two solutions. Thanks.
I ended up using something similar to Wylie Кулик's answer with a few changes:
I didn't want to switch to Redux for just this one use-case. So I used the component state of my top-level component (i.e. a component higher up the tree).
I cached the form's state on the form component's componentWillUnmount and restored the cached state on componentDidMount.
I passed the cached state as a prop from the higher component to the child component.
It ended up being a very small amount of code and is working like a charm so far.
Use Redux to have a state store which transcends any particular component. Then in your component, as part of the form submission process, dispatch an action with payload of all of the form data. This should be cached on state and then when the component is remounted by your navigation structure, it should have access to this cache via Reduxsconnectfunctions mapStateToProps method. You can repopulate your form from that.
It's not clear from your question whether or not you are submitting the form in the traditional old way. I would use e.preventDefault in the handler instead, and have all the form data on the component's state, this can be sent to Redux's state store as described above, and Ajaxed off with superagent or similar. At the same time it can be cached.
Redux: http://redux.js.org

What to store in redux state?

I'm building a medium-sized React/Redux app, and I've become very comfortable with React - however, Redux is still a little hard to wrap my head around.
I understand that I can use connect() from Redux to connect any Component or Container to Redux state. However, I'm unclear on when to do this - is it based on complexity? How many props would need to be passed down to child components?
What are the factors I can use to determine when to use connect()?
Edit to provide an example: -----
For example, I'd like to include a messages area for users inside my app, particularly a badge showing number of unread messages. Would I simply connect() any component where I'd like to display the badge?
I DON'T agree about storing all component state in the store. I prefer having in the redux store only data that matters to application as a whole and thus other components may benefit from this global accessible shared data.
Having component specific state in the store, that only matters to this component, is a overkill and useless IMO.
You store the state of your app in redux. How you structure your state tree is up to you. You can think of the state tree as one giant javascript object. With redux, you would ideally store as little component state in your react components themselves and instead move that to the redux state tree.
For example, if you fetched some user data, you could store that in the redux state such that your connected components have access to that data now. You can also get more granular and store states that describe certain UI components. A part of your state that describes a dropdown could look like this
{
myDropdown: {
isOpen: false,
options: [
'apple',
'orange'
]
}
}
I believe a good point to start incorporating redux is when your app gets to a certain point where your components are no longer just "dumb" components that display data.
Edit:
To try and answer the question "when should I connect my components?". I struggled with this myself but don't have a great answer yet. Right now I typically connect a component if I am passing down props through many ancestor components just for that component specifically. So connecting would avoid that boilerplate code altogether.
Official REDUX page:
https://redux.js.org/faq/organizing-state#do-i-have-to-put-all-my-state-into-redux-should-i-ever-use-reacts-setstate
Some common rules of thumb for determining what kind of data should be put into Redux:
Do other parts of the application care about this data?
Do you need to be able to create further derived data based on this original data?
Is the same data being used to drive multiple components?
Is there value to you in being able to restore this state to a given point in time
Do you want to cache the data
List item
But...that means in most of off applications the only data what I should store in Redux store is the logged in user data. That is the only entity which attributes influences all the screens (role, login name, user settings).
Usual applications do not need to remember entered data between screens, cache, history....
Very confusing, so I am not really sure any more what to put in Redux store...

In Redux, should global state replace component state?

My question is, should I still be using stateful React components or should I move that state into the Redux store?
There is no single true answer for you question.
You have different types of states. You have a state of your models (in terms of MVC) and UI (View) state. In classical MVC your models should not depend on UI. So, here we have a question: is it ok to save UI state (inputs, checkboxes state) in global redux store.
The most general rule, in this case, is to use common sense :). You can choose any of the approaches depending on your needs and it will be ok if it suits better for your situation.
But, let's look at several examples.
global redux store for everything
I know apps, that save whole UI state in global redux store. I mean that every keystroke in any field will fire event and will update the global store.
Pros:
It is easy to track state changes when the whole state is in one place.
You can serialize the whole state for debugging purposes. It can be automatic state saving on errors. Or QA engineer can dump UI state with a special keyboard shortcut and send to developers. Developers can take this serialized state and restore whole UI as it was on QA's machine.
Cons:
Rerender the whole app on every keystroke.
A lot of intermediary state (in global store) that is needed only while user entering some data.
Passing state down to your components. You will use "Container" components for this but the question is should your "Container" components be only top-level components or you should wrap leaf dump components in containers. Both variants are acceptable but in most cases it is better to move state higher (while it makes sense). Read about "Smart vs Dumb" components or "Containers vs Presentational components"
You should manage different types of state (from different sources) in one global store.
UI state in your components.
For example, you have a form. And your form manages the state on your inputs by its own. So you just render it as <Form onSubmit={ (fields) => saveFields(fields) }>
Pros:
Intermidate form state is private to form. You can think that this state does not exist at all, it does not matter for you.
The shape of private state is much easier to change.
Components are more coherent. They are more independent, like simple mini applications inside your larger application.
Cons:
Other components cannot access this state.
There is no single place of storing state.
Different appoaches to state management.
Increases possibilty of situations when there will be more than one source of thruth.
Additional resources:
Presentation from ReactConf 2016 about possible options for managing state in ReactJS apps
Dan Abramov's great post about "Container" and "Presentational" components
Great video tutorial from Dan Abramov "Getting started with redux". It shows how to use presentational components and how to manage app state.
Some general ideas that can be useful:
Handle as less state as possible in your components but not less than required. Stateless components are easier to work with. But remeber that the state will be moved somewhere, so you will need to handle it in any case (it can be store, or presentational wrapper component etc).
Make your components as much independent as possible. You can make good independent components with private state or make them stateless.
Split components into presentational components (context independent) and container components (context dependent).
Move state as high as possible. Prefer saving state in upper level components. It can be not only container components. You can create presentational components that wraps you stateless components just to manage state (they will have no connection to redux)
I recommend reading this Medium post: Presentational and Container Components. It outlines the ideas of using component state for UI state but non-UI state is global (redux). It also suggest a pattern of how to approach that by having container components responsible for managing access to the global state and simple view components that the container passes state to as a prop.
So the answer is a little more complicated in my opinion because there are different types of state.
I highly recommend this free video series that goes into Redux in depth and provides a lot of explanation to build your knowledge up quickly: Getting Started with Redux.
After digging into Redux more and using it on a project to learn, I found myself making use of it to store UI state. The particular use case was a long scrolling div. I wanted the scroll position of the div to be the same when the back button was used. It was super easy to hook the click up to a dispatch to update the state for the current div.scrollTop and then on componentMount (back button pressed, component remounts) simply set the div.scrollTop to the position from state.
So I think it can be very useful to have UI state in Redux too. It is easier to reason about and simple to do. I can see building very powerful UIs this way that do not exhibit the typical UI issues seen with single page applications.

React && Flux confused about where to put data

I'm developing a web app with React + Flux. But sometimes, I am confused about where to put the data of a component.
Flux says that we should keep the data in the store. When the data changed, store should emit a change event, then the react components which listen to the store's change event should call setState with the data in the store.
But in this way, one react component is made by two parts, which are the component it self, and the store to be listened. Sometimes I want the component to be more individual. I don't want some state of this component to be related to any store, so I store the state in the component jsx file. In this way it is not a flux style, but just react.
I'm not sure if I'm doing the right thing. Should a fluxible app to be totally obey the flux or not?
There is no right answer to this question.
You could differentiate between application state and view state just as much as you could reason that all state should live in one global store.
Application state could be User information, product information or that type of data whereas view state could be related to toggling a div or what color a link should have depending on the application state.
These two approaches are both used in the wild and there is just a matter of preference.
This is a good read that argues for the case of a single state.
I won't link to the other reasoning as it's the "flux way" and an easy Google

Resources