splide icon indicating copy to clipboard operation
splide copied to clipboard

Components.Layout.listSize() === 0 on mounted event

Open pryley opened this issue 3 years ago • 0 comments

Checks

  • [X] Not a duplicate.
  • [X] Not a question, feature request, or anything other than a bug report directly related to Splide. Use Discussions for these topics: https://github.com/Splidejs/splide/discussions

Version

v4.0.7

Description

I am changing the number of slides per page based on the width of the slider.

function resizeSwiper (minsize, maxslides) {
  let width = this.Components.Layout.listSize();
  let slides = Math.max(1, Math.floor(width / +minsize));
  let perPage = Math.min(slides, +maxslides || 6);
  this.options = { perPage };
}

const splide1 = new Splide('#carousel1', {
  gap: 16,
  drag: 'free',
  perMove: 1,
  perPage: 1,
  snap: true,
});

splide1.on('mounted resize', resizeSwiper.bind(splide1, 200, 6))

splide1.mount()

The problem here is that the slider width is 0 when the mounted event is triggered, so the perPage option is not calculated correctly on mount.

If I delay the mounted callback by a few milliseconds, the slider width is correct:


splide1.on('mounted', () => setTimeout(resizeSwiper.bind(splide1, 200, 6), 50))
splide1.on('resize', resizeSwiper.bind(splide1, 200, 6))

splide1.mount()

Seems like a race condition is involved here...

Reproduction Link

https://codesandbox.io/s/condescending-bush-vwzfbt

Steps to Reproduce

  1. Open https://codesandbox.io/s/condescending-bush-vwzfbt
  2. Refresh the Browser panel (to prevent the resize event from being triggered on page load)

Expected Behaviour

I expect the perPage option to be updated correctly on the mounted event without using a setTimeout.

pryley avatar Jul 31 '22 11:07 pryley