reactjsreact-hooksdatepickermui-x-date-picker

Check two MUI date pickers for value and show/hide another component


I have two date pickers with a start date and end date

<Box sx={{ display: "flex", gap: 2, flexWrap: "wrap" }}>
                  <DatePicker
                    sx={{ flex: 1, minWidth: "150px" }}
                    label="Start day"
                    onAccept={handleStartDateChanged}
                  />
                  <DatePicker
                    sx={{ flex: 1, minWidth: "150px" }}
                    label="End day"
                    onAccept={handleEndDateChanged}
                  />
                </Box>
{periodSet ? (
              <Capacity timelineStart={startDate} timelineEnd={endDate} />
            ) : null}
const [startDate, setStartDate] = useState(null);
  const [endDate, setEndDate] = useState(null);
  const [periodSet, setPeriodSet] = useState(false);

  const handleStartDateChanged = (e) => {
    setStartDate(e);
    setPeriodSet(startDate && endDate);
    console.log(periodSet);
  };
  const handleEndDateChanged = (e) => {
    setEndDate(e);
    setPeriodSet(startDate && endDate);
    console.log(periodSet);
  };

when there is a date selected for both of them I want to show a component fetching data for this specific period of time. I'm already struggling with show and hide of this component. The component is not shown after selecting both dates. You need a third selection to show the component. I assume this is due to incomplete async setting of startDate and endDate before setting periodSet. Is there some kind of a callback when state change is finished? or is there some more elegant ways like binding or similar? or better use hooks like useEffect or whatever? Sorry if this question is kind of stupid. I'm very new to React

I was trying different things like this try of a callback, but behavior wasn't as expected

setStartDate((e) => {
      setPeriodSet(startDate && endDate);
    });

Solution

  • You don't need state for this. Just regular variable

    const periodSet = Boolean(startData && endDate)