0

I have a form in react js where user can add values.

const Demo = () => {
  const [date, setDate] = useState("");
  const onFinish = values => {
    console.log("Received values of form:", values);
  };

  const changeDate = v => {
    console.log(moment(v).format("HH"));
    setDate(moment(v).format("HH"));
  };

  return (
    <Form name="dynamic_form_nest_item" onFinish={onFinish} autoComplete="off">
      <Form.List name="users">
        {(fields, { add, remove }) => {
          return (
            <div>
              {fields.map(field => (
                <Space
                  key={field.key}
                  style={{ display: "flex", marginBottom: 8 }}
                  align="start"
                >
                  <Form.Item
                    {...field}
                    name={[field.name, "first"]}
                    fieldKey={[field.fieldKey, "first"]}
                    rules={[{ required: true, message: "Missing first name" }]}
                  >
                    <Input placeholder="First Name" />
                  </Form.Item>

                  <TimePicker
                    defaultValue={moment("12:08", format)}
                    format={format}
                    onChange={changeDate}
                  />
                  <p>{date}</p>
                  <MinusCircleOutlined
                    onClick={() => {
                      remove(field.name);
                    }}
                  />
                </Space>
              ))}

              <Form.Item>
                <Button
                  type="dashed"
                  onClick={() => {
                    add();
                  }}
                  block
                >
                  <PlusOutlined /> Add field
                </Button>
              </Form.Item>
            </div>
          );
        }}
      </Form.List>

      <Form.Item>
        <Button type="primary" htmlType="submit">
          Submit
        </Button>
      </Form.Item>
    </Form>

There i have an issue when i try to set time in different components. For example:
User clicks on Add fields button 2 times appears 2 blocks of inputs where he could adds data. Then trying to set time in one component the value also is changing on the another component.
Why this happening and how to solve the issue?
demo: https://codesandbox.io/s/peaceful-leavitt-yus0q?file=/index.js:337-2286

Asking
  • 3,487
  • 11
  • 51
  • 106
  • 1
    You seem to be having ***a single*** state variable changed from within all of datepickers. Assuming, you 'll need separate values for all of them, you're supposed to be having an array of dates, rather than single value. You may check out [this post](https://stackoverflow.com/a/60265345/11299053) as a reference. – Yevhen Horbunkov Jul 06 '20 at 08:36
  • @YevgenGorbunkov, could you take a lok here please https://codesandbox.io/s/peaceful-leavitt-yus0q?file=/index.js, the text now is changing ok, but when i try to change a text or another, the text still as previous. How could i to solve this? – Asking Jul 06 '20 at 09:07

1 Answers1

0

Try this, i have added comments with changing: codeSandBox: https://codesandbox.io/s/thirsty-liskov-yek2y?file=/index.js

    import React, { useState } from "react";
    import ReactDOM from "react-dom";
    import "antd/dist/antd.css";
    import "./index.css";
    import { Form, Input, Button, Space } from "antd";
    import { MinusCircleOutlined, PlusOutlined } from "@ant-design/icons";
    import { TimePicker } from "antd";
    import moment from "moment";
    
    const format = "HH:mm";
    const Demo = () => {
      const [date, setDate] = useState({}); //use a date object to store every field value against every key

      const onFinish = values => {
        console.log("Received values of form:", values, date);
      };
    
      const changeDate = (momentDate, dateString, key) => {
        console.log(momentDate, dateString, key);
        setDate({ ...date, [key]: dateString });
      };
    
      return (
        <Form name="dynamic_form_nest_item" onFinish={onFinish} autoComplete="off">
          <Form.List name="users">
            {(fields, { add, remove }) => {
              return (
                <div>
                  {fields.map(field => (
                    <Space
                      key={field.key}
                      style={{ display: "flex", marginBottom: 8 }}
                      align="start"
                    >
                      <Form.Item
                        {...field}
                        name={[field.name, "first"]}
                        fieldKey={[field.fieldKey, "first"]}
                        rules={[{ required: true, message: "Missing first name" }]}
                      >
                        <Input placeholder="First Name" />
                      </Form.Item>
    
                      <TimePicker
                        defaultValue={moment("12:08", format)}
                        format={format}
                        onChange={(date, dateString) =>
                          changeDate(date, dateString, field.key) //here passing date & key to store
                        }
                      />
                      <p>{date[field.key]}</p>
                      <MinusCircleOutlined
                        onClick={() => {
                          remove(field.name);
                        }}
                      />
                    </Space>
                  ))}
    
                  <Form.Item>
                    <Button
                      type="dashed"
                      onClick={() => {
                        add();
                      }}
                      block
                    >
                      <PlusOutlined /> Add field
                    </Button>
                  </Form.Item>
                </div>
              );
            }}
          </Form.List>
    
          <Form.Item>
            <Button type="primary" htmlType="submit">
              Submit
            </Button>
          </Form.Item>
        </Form>
      );
    };
    
    ReactDOM.render(<Demo />, document.getElementById("container"));
bakar_dev
  • 936
  • 4
  • 13
  • could you take a look please here https://codesandbox.io/s/runtime-bird-6mlfs?file=/index.js . I try to count the difference of hours using your answer but when i count for the second form, the previous is gone. Could you help? – Asking Jul 06 '20 at 11:22
  • Save the difference in object with key reference like i did before for the date. – bakar_dev Jul 06 '20 at 11:32
  • i did this `moment.duration(endTime[k].diff(startTime)[k])` but it does not work. Could you show please, because i don't understand how it should look. Thank you – Asking Jul 06 '20 at 11:35
  • visit this you will find your solution: https://stackoverflow.com/questions/25150570/get-hours-difference-between-two-dates-in-moment-js – bakar_dev Jul 06 '20 at 11:45
  • i created a function to count de difference, but the issue is that the next value overrides previous. – Asking Jul 06 '20 at 11:52