Y
Y
yanis_kondakov2017-02-26 08:05:23
React
yanis_kondakov, 2017-02-26 08:05:23

Where to store the current form value?

Hello. Actually I write on reactJs + redux.
There are forms, and now, when information changes there, I store the changing information in the state of this particular component, and when the save button is pressed, I send it to the database and, accordingly, to the state of the entire application.
The question arose, is it worth declaring these current state in the state of the entire application and changing them there? How appropriate, optimized, and so on. What is considered best practices here?
update.
I'll update the question with a link to an example.
And some code

spoiler
state = {
    currentDepartment: {
      name: ''
    }
  }
  
  // make request to DB
  componentWillMount() {
    this.props.fetchDepartments();
    this.props.fetchDepartment(+this.props.params.departmentId);
  }
  
  // set current state value from DB
  componentWillReceiveProps(nextProps) {
    this.setState({
      currentDepartment: {
        name: nextProps.singleDepartment.name
      }
    });
  }

  // change current state data on input change
  handleInputChange = (evt) => {
    const target = evt.target;
    const value = target.value;
    const name = target.name;
    this.setState({
      currentDepartment: {...this.state.currentDepartment, [name]: value}
    });
  }

  // send updated data to DB
   handleUpdate = (evt) => {
    evt.preventDefault();
    const previousDepartment = h.findById(this.props.singleDepartment.id, this.props.departments);
    const updatedDepartment = h.updateItem(previousDepartment, this.state.currentDepartment);
    this.props.saveDepartment(updatedDepartment);
  }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim, 2017-02-26
@yanis_kondakov

I store changing information in the state of this particular component

This is logical, for this (changeable properties of the component) state was invented.
As I understand it, the state of the entire application means either the redux store or the state of some parent component. If the second is definitely not, because when it changes, the entire application (all descendants) will be redrawn, but if we are talking about the redux store, then some data that you need in other places (except for the current component) should be put there, but while keeping in mind that all components that are "subscribed to this data" (using the connect function ) will be redrawn when changed.
ps answering the question "where to store the current form value?" - I would store it in the state of the component, since usually it is not needed anywhere else in other components.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question