Skip to content

useCalendarState start date doesn't recalculate when updating visibleDuration #7809

@paddyjoneill

Description

@paddyjoneill

Provide a general summary of the issue here

I'm creating a mobile calendar and when I scroll up I want to add the previous months. I am doing this by increasing the visibleDuration.

When the visibleMonths is updated the value of the startDate is not recalculated and therefore my calendar never goes before the initial startDate.

🤔 Expected Behavior?

When updating visibleDuration the startDate will be recalculated.

😯 Current Behavior

When updating visibleDuration the startDate is not recalculated.

💁 Possible Solution

I have copied the source code and amended locally and made the change below

Before:

  let [startDate, setStartDate] = useState(() => {
    switch (selectionAlignment) {
      case 'start':
        return alignStart(focusedDate, visibleDuration, locale, minValue, maxValue);
      case 'end':
        return alignEnd(focusedDate, visibleDuration, locale, minValue, maxValue);
      case 'center':
      default:
        return alignCenter(focusedDate, visibleDuration, locale, minValue, maxValue);
    }
  });

After:

  const calculateStartDate = () => {
    switch (selectionAlignment) {
      case 'start':
        return alignStart(
          focusedDate,
          visibleDuration,
          locale,
          minValue,
          maxValue
        )
      case 'end':
        return alignEnd(
          focusedDate,
          visibleDuration,
          locale,
          minValue,
          maxValue
        )
      case 'center':
      default:
        return alignCenter(
          focusedDate,
          visibleDuration,
          locale,
          minValue,
          maxValue
        )
    }
  }

  const [startDate, setStartDate] = useState(() => calculateStartDate())

  const visibleDurationRef = useRef(visibleDuration)

  useEffect(() => {
    if (visibleDuration.months !== visibleDurationRef.current.months) {
      visibleDurationRef.current = visibleDuration
      setStartDate(calculateStartDate())
    }
  }, [visibleDuration])

If you would like me to open a PR let me know and I can also create a CodeSandbox or similar to show.

🔦 Context

No response

🖥️ Steps to Reproduce

to follow

Version

3.6.0

What browsers are you seeing the problem on?

Chrome

If other, please specify.

No response

What operating system are you using?

MacOS

🧢 Your Company/Team

No response

🕷 Tracking Issue

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions