Skip to content

Commit f7040e6

Browse files
committed
Safer step next/back logic
1 parent e689253 commit f7040e6

File tree

1 file changed

+15
-26
lines changed

1 file changed

+15
-26
lines changed

static/app/components/featureShowcase.tsx

Lines changed: 15 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,6 @@ import {
33
createContext,
44
isValidElement,
55
useContext,
6-
useEffect,
7-
useRef,
86
useState,
97
type ReactElement,
108
type ReactNode,
@@ -129,46 +127,35 @@ type FeatureShowcaseProps = ModalRenderProps & {
129127
* ));
130128
* ```
131129
*/
132-
function FeatureShowcase({
133-
closeModal,
134-
children,
135-
onStepChange,
136-
onClose,
137-
}: FeatureShowcaseProps) {
130+
function FeatureShowcase({closeModal, children, onStepChange}: FeatureShowcaseProps) {
138131
const [current, setCurrent] = useState(0);
139-
const stateRef = useRef({current: 0, onClose});
140-
stateRef.current = {current, onClose};
141-
142-
useEffect(() => {
143-
return () => {
144-
stateRef.current.onClose?.(stateRef.current.current);
145-
};
146-
}, []);
147132

148133
const steps = Children.toArray(children).filter(
149134
(child): child is ReactElement => isValidElement(child) && child.type === Step
150135
);
151136

137+
const stepCount = steps.length;
138+
const hasNext = current < stepCount - 1;
139+
const hasPrevious = current > 0;
140+
const activeStep = steps[current] ?? steps[stepCount - 1];
141+
152142
const handleAdvance = () => {
153-
const nextStep = current + 1;
143+
const nextStep = Math.min(current + 1, stepCount - 1);
154144
if (nextStep !== current) {
155145
setCurrent(nextStep);
156146
onStepChange?.(nextStep);
157147
}
158148
};
159149

160150
const handleBack = () => {
161-
if (current > 0) {
162-
setCurrent(current - 1);
151+
const prevStep = Math.max(current - 1, 0);
152+
if (prevStep !== current) {
153+
setCurrent(prevStep);
154+
onStepChange?.(prevStep);
163155
}
164156
};
165157

166-
const stepCount = steps.length;
167-
const hasNext = current < stepCount - 1;
168-
const hasPrevious = current > 0;
169-
const activeStep = steps[current] ?? steps[stepCount - 1];
170-
171-
const ctx: ShowcaseContextValue = {
158+
const contextValue: ShowcaseContextValue = {
172159
current,
173160
stepCount,
174161
hasNext,
@@ -185,7 +172,9 @@ function FeatureShowcase({
185172
<IconClose size="xs" />
186173
</Button>
187174
</Flex>
188-
<ShowcaseContext.Provider value={ctx}>{activeStep}</ShowcaseContext.Provider>
175+
<ShowcaseContext.Provider value={contextValue}>
176+
{activeStep}
177+
</ShowcaseContext.Provider>
189178
</Container>
190179
);
191180
}

0 commit comments

Comments
 (0)