top-down rendering - how to solve state in pre-populated input fields

115 views Asked by At

Scenario: I have an react app which has its state in flux store (async load), passing data down to Root component which is passing data to its children and so on.

now: text input field, nested somewhere deep down in node tree, has its initial value done in getInitialState from a prop (the prop has been passed down), and on onChange event its state is set to typed value. So far book example. Now let's 'submit' the form, action is triggered, ajax call has been made, data came back changed, passed to the store which emits event to Root component, the node tree gets re-rendered again, BUT of course getInitialState is not triggered again, and the field still has the last typed in value. I don't think I want to initiate the whole action-store-root-children-reRender loop on every single key stroke, right?

Question: How do I get the input's state to be fresh from the passed prop (the store one)

THOUGHT: Hmm, I can actually tell when I'm initiating re-render from the ROOT, by setting a store 'flag' in ROOT's componentWillUpdate() then setting it back in componentDidUpdate() - then all the child components can know if it is ROOT intent to re-render or just a parent non-store initiated change.

2

There are 2 answers

0
Jed Richards On

Keep the form's values in the store instead, and don't using any local component state at all. When the form is edited trigger actions to update the store and re-render the app.

4
Max Bumaye On

First of all what you are doing is an antipattern. State should not be set equal to props. Your props should not be state.

The React docs are pretty clear on updating props. Check out this link: https://facebook.github.io/react/docs/component-specs.html

componentWillReceiveProps(object nextProps)

You should think about implementing this lifecyclemethod it will help you to be aware of prop changes.

But please think about seperating props and state - there is a reason why React Framework has both. But that is a different topic.

EDIT1: If you want to update your stores state then call a flux action that referes to the corresponding store and pass in the props as payload inside of the lifecyclemethod above.

Hope this helped.