0

I am currently working on a multi-step form to post to the server and I am trying to the data using onChange as an event handler to get the data from the inputs. I used the following code to handle the input :

handleChange = input => e => {
        this.setState({ [input]: e.target.value });
    };

And in the form, I created an object to include data that need to be sent later to the server. And here is how I did this and then stored all values inside an object name values:

   const { first_name, last_name, phone, special_instructions, email, category, total_amount, delivery_date
            , delivery_address, pickup_address, source, payment_method, invoice_number,
            delivery_amount, delivery_address_id, pickup_address_id, pickup_date, invoiced_amount } = this.state;

        const values = {
            first_name, last_name, phone, special_instructions, email, category, total_amount, delivery_date
            , delivery_address, pickup_address, source, payment_method, invoice_number,
            delivery_amount, delivery_address_id, pickup_address_id, pickup_date, invoiced_amount
        };

The thing is when I try to enter data using the following line

<Input type="date" name="pickup_date" onChange={handleChange('pickup_date')} value={values.pickup_date} />

<Input type="text" name="nickname" onChange={handleChange('nickname')} value={values.pickup_address.nickname} />

The first one works pretty well and accepts input but the second one doesn't because it needs data inside the object names "pickup_address". Also, you can check the data of the values here : You can check the values data right here

I just wonder if something might change in the onChange handler to fit both types of data that are inside the object values and the pickup_address object too which is already inside the object values. Thanks in advance.

Yevhen Horbunkov
  • 14,965
  • 3
  • 20
  • 42
Saif
  • 249
  • 5
  • 15
  • Your scenario seems to be a good use case for [Redux](https://react-redux.js.org/) to manage your complex state. If designed properly, universal reducer may be used to modify deeply nested properties. Without Redux, I would say, keeping your scattered form elements controlled would require certain advanced techniques (e.g. [forwarding Refs](https://reactjs.org/docs/forwarding-refs.html)). But all that is way too far from the problem stated in current topic. – Yevhen Horbunkov Jul 02 '20 at 21:15
  • I have connected the form to redux and it works pretty well. Yet, the reducer doesn't modify the initial state accordingly Idk why. Here is the updated link of redux setup : https://codesandbox.io/s/funny-haslett-chj9j?file=/src/index.js – Saif Jul 03 '20 at 16:44
  • I hope that you can take a look and help solve this problem. Thanks in advance. – Saif Jul 03 '20 at 16:44

0 Answers0