React-dates: Trigger onDatesChange only when BOTH dates are selected

Created on 12 Mar 2018  路  6Comments  路  Source: airbnb/react-dates

Current behaviour for DateRangePicker is that onDatesChange is triggered on EVERY date select, to and from

How to trigger onDatesChange only when BOTH dates has been selected? I know I can compare new and current dates, but I want to avoid this kind of hacking. It there some out of the box approaches?

`to` => `from` => onDatesChange( only now it is triggered )

All 6 comments

Just adding an if or 2 on your onDatesChange would be it .

function onDatesChange({startDate, endDate}) {
    if(!startDate || !endDate) return;
    if(!startDate.isValid() || !endDate.isValid()) return;
    // your code here 
}

@amivag @wzup @linorabolini since the parent component of the datepicker holds the startDate/endDate values in state, doesn't it have the information it needs to determine whether or not the user has finished selecting a range? Can you describe your usecase a bit more and why it can't be handled by the parent component?

@majapw hey im saying the same thing. It should be logic that the parent component should handle ! i just provided the snippet haahah

@wzup If @linorabolini's solution didn't work for you (it wasn't exactly what I needed) this might help: http://www.bryanhadro.com/2018/05/04/final-ondateschange-with-react-dates/

Hi, Can someone guide me how this was achieved? I am not sure exactly whats needs to be done to trigger the action when the user selected both the dates?
Thanks in advance.

Here is my solution:

  const [stateStartDate, updateStateStartDate] = useState(null)
  const [stateEndDate, updateStateEndDate] = useState(null)

  const refreshDates = () => {
    updateStateStartDate(null)
    updateStateEndDate(null)
  }

const updateDateData = async ({ startDate, endDate }) => {
    if (focusedInput === 'startDate') {
      refreshDates()
      updateStateStartDate(startDate)
      return
    }
    if (focusedInput === 'endDate') {
      updateStateEndDate(endDate)
    }

    if (stateStartDate && stateEndDate) {
      // DO STUFF
      updateFocusedInput(null)
      // DO STUFF
      }
    }
  }

<DateRangePicker
      .
      .
   startDate={stateStartDate}
   endDate={stateEndDate}
   onDatesChange={updateDateData}
      .
      .
      />
Was this page helpful?
0 / 5 - 0 ratings