G
G
GavrilovArtem2019-10-06 12:40:48
JavaScript
GavrilovArtem, 2019-10-06 12:40:48

React how not to overwrite nested object in state?

Parent component has state initialization

state = { 
  tasks: {},
  users: {
    userId: 1,
    userName: "Artem Gavrilov",    
  },
  appData: {
    selectedDate: new Date(),
    unfinished: {},
  }, 
};

There is a child component with a form of text inputs.
export default class Form extends React.Component {
  handleTextChange = (e) => {
    e.preventDefault();
    const {name, value} = e.target;
    this.setState({...this.state, appData: {
      unfinished: {
        [name]: value,
        }
      }
    });
  }
  render() {
    return (
      <div className="task-container">
        <form className="task-form">
          <div className="task-line">
            <p className="task-p">Название задачи</p>
            <input onChange={this.handleTextChange} className="task-input" type="text" required name="taskName"/>
          </div>
          <div className="task-line">
            <p className="task-p">Описание задачи</p>
            <textarea onChange={this.handleTextChange} className="task-textarea" cols="20" rows="5" type="text" required name="taskDesc"/>
          </div>
        </form>
      </div>
    );
  }
}

I want to populate the state.appData.unfinished object with the current values ​​from the inputs. The problem is that when entering characters in the second field - state is overwritten and I lose the value from the first (and vice versa). If I write to state.[name], everything works correctly, but I want to work with such a state structure. How to stop overwriting state in nested object?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2019-10-06
@GavrilovArtem

this.setState(({ appData }) => ({
  appData: {
    ...appData,
    unfinished: {
      ...appData.unfinished,
      [name]: value,
    },
  },
}));

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question