Skip to content

Commit ddc0834

Browse files
authored
Carousel: subscribe before calling setApi (#214)
The lint fix in #211 left the listeners in an effect declared after the one that calls setApi. Effects run in order, so a consumer that scrolls as soon as it gets the api (e.g. `setApi={(api) => api?.scrollTo(2, true)}`) moved the carousel before anyone was listening. The triggers and indicators then stayed on slide 1. Subscribing first fixes it, with no setState in an effect.
1 parent 89923e1 commit ddc0834

1 file changed

Lines changed: 8 additions & 6 deletions

File tree

‎components/application/carousel/carousel-base.tsx‎

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -109,12 +109,8 @@ const CarouselRoot = ({ orientation = "horizontal", opts, setApi, plugins, class
109109
[scrollPrev, scrollNext],
110110
);
111111

112-
useEffect(() => {
113-
if (!api || !setApi) return;
114-
115-
setApi(api);
116-
}, [api, setApi]);
117-
112+
// Subscribe before handing the api to setApi: effects run in order, so a consumer that
113+
// scrolls as soon as it gets the api must find these listeners already attached.
118114
useEffect(() => {
119115
if (!api) return;
120116

@@ -129,6 +125,12 @@ const CarouselRoot = ({ orientation = "horizontal", opts, setApi, plugins, class
129125
};
130126
}, [api, onInit, onSelect]);
131127

128+
useEffect(() => {
129+
if (!api || !setApi) return;
130+
131+
setApi(api);
132+
}, [api, setApi]);
133+
132134
return (
133135
<CarouselContext.Provider
134136
value={{

0 commit comments

Comments
 (0)