简体   繁体   中英

REACT- How to set enddate same as startdate by default but control if enddate not before startdate?

if a user select a starting date, by default I would like that this selection would be the same for the ending date. And then if the user wants to change this ending date, he can. For now, I can select the starting date and the ending date.

And putting a condition on my date ie not able to put an ending date that is before a starting date.

Here is my code :

export default function SelectionChoice({ next, selChoice2, setSelChoice2 }) {
  const [summary, setSummary] = useState("");
  const [start, setStart] = useState("");
  const [end, setEnd] = useState("");
  const [selChoice1, setSelChoice1] = useState();
  const [data, setData] = useState([])


  useEffect(() => {
    myApi.functionA()
      .then((res) => {
        console.log(res);
        setData(res.data.data);
      })
      .catch((err) => {
        console.log(err);
      });
  }, []);

  ...
  const choice1 = data?.map((item) => {
    return {
      label: item.name,
      value: item.id
    };
  });

  const choice2 = data?.flatMap((item) => {
    return item.choice2.map((c) => ({
      label: c.name,
      value: c.id
    }));
  });

  const textChange = (e) => {
    if (e?.target?.id === undefined) return setSelChoice1(e);
    if (e?.target?.id === undefined) return setSelChoice2(e);
    switch (e.target.id) {    
    ...
      case "start":
        setStart(e.target.value);
        break;
      case "end":
        setEnd(e.target.value);
        break;
      default:
    }
  };
  return (
    <>
      <form>
        <div >
          Choose choice1 and choice2
        </div>
        <div>
          <label>
            Choice1:
            <CustomDropdown
              options={choice1}
              value={selChoice1}
              setValue={setSelChoice1}
              isMulti={true}
            />
          </label>
          <label>
            Choice2:
            <CustomDropdown
              options={choice2}
              value={selChoice2}
              setValue={setSelChoice2}
              isMulti={true}
            />
          </label>
        </div>
        <div>
          <label>
            Start:
            <div>
              <input
                type="date"
                name="start"
                value={start}
                onChange={textChange}
                id="start"
              />
            </div>
          </label>
          <label>
            End:
            <div>
              <input
                type="date"
                name="end"
                value={end}
                onChange={textChange}
                id="end"
              />
            </div>
          </label>
          <p className="formfield">
            <label
              for="summary"
            >
              Description :
              <textarea
                value={summary}
                onChange={textChange}
                name="summary"
                id="summary"
                cols="10"
                rows="10"
              />
            </label>
          </p>
        </div>
      </form>
        <button
          onClick={() =>
            next({           
              ...,
              start,
              end
            })
          }
        >
          Next
        </button>
    </>
  );
}

You can check if the end date is having any value while updating the start date and set it if it is not having any value.

switch (e.target.id) {
  case "start":
    setStart(e.target.value);
    if (!end) {
      setEnd(e.target.value);
    }
    break;
  case "end":
    if (e.target.value >= start) {
      setEnd(e.target.value);
    } else {
      //flash error message
    }
    break;
  default:
}

I would like you update the code like below for checking possible cases. And I also updated the Async Function with async/await.

export default function SelectionChoice({ next, selChoice2, setSelChoice2 }) {
  ...
  const [start, setStart] = useState("");
  const [end, setEnd] = useState("");
  ...

  useEffect(() => {
    /*
    myApi.functionA()
      .then((res) => {
        console.log(res);
        setData(res.data.data);
      })
      .catch((err) => {
        console.log(err);
      });
      */

    const getData = async () => {
      try {
        const res = await myApi.functionA();
        setData(res.data.data);
      } catch(err) {
        console.log(err)
      }
    }

    getData();

  }, []);

  const textChange = (e) => {
    switch (e.target.id) {    
      case "start":
        setStart(e.target.value);
        const startDate = new Date(e.target.value).getTime();
        const endDate = new Date(end).getTime();

        // Check if end date is not set 
        // Or End Date is before Start Date
        if (!!end || startDate > endDate) {
          setEnd(e.target.value)
        }
    
        break;
      case "end":
        const endDate = new Date(e.target.value).getTime();
        const startDate = new Date(start).getTime();

        // Check End Date is before the Start Date
        if (endDate < startDate) {
           setEnd(start);
        } else {
           setEnd(e.target.value);
        }
      
        break;
      default:
        break;
    }
  };

  return (
    ...
  )

Hope this would help you even a little.

Thanks

请注意您的结束日期不要早于您的开始日期

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM