Im trying to make a function that will navigate the user to the steps that are not disabled, and that skips the disabled steps.
I wrote the following code, but it does not behave how i would like it to.
Expected behaviour assuming the current step is Step 5:
On Button Click Step 5 to Step 3 on Button click Step 3 to Step 1
But currently the behaviour is like this:
On button click Step 5 to Step 1
I want to make the loop the stop on step 3, i tried to add a breakpoint, but that did not solve it, i am running out of ideas
const steps = [
{ title: 'Step 1', id: 'stp1', disabled: false, },
{ title: 'Step 2', id: 'stp2', disabled: true, },
{ title: 'Step 3', id: 'stp3', disabled: false, },
{ title: 'Step 4', id: 'stp4', disabled: true, },
{ title: 'Step 5', id: 'stp5', disabled: false, },
]
const [currentStepIndex, setCurrentStepIndex] = useState(4);
const getPreviousSelectableStep = () => {
const steps = args.steps
let stepIndex = currentStepIndex
if ((stepIndex > 0) && steps[stepIndex - 1].disabled === true) {
for (var i = steps.length - 1; i >= 0; i--) {
if (steps[i].disabled === false) {
setCurrentStepIndex(i)
setCurrentStepId(steps[i].id)
break
}
}
} else if (stepIndex > 0) {
setCurrentStepIndex(stepIndex - 1)
setCurrentStepId(steps[stepIndex - 1].id)
}
}
CodePudding user response:
In your if
condition start the loop from startIndex - 1
and not from the end steps.length - 1
.
if (stepIndex > 0 && steps[stepIndex - 1].disabled === true) {
for (var i = stepIndex - 1; i >= 0; i--) {
if (steps[i].disabled === false) {
setCurrentStepIndex(i);
setCurrentStepId(steps[i].id);
break;
}
}
} else if (stepIndex > 0) {
setCurrentStepIndex(stepIndex - 1);
setCurrentStepId(steps[stepIndex - 1].id);
}
CodePudding user response:
function getPrevStep(number)
{
let data = steps.filter(x => !x.disabled).reverse()
return data[data.findIndex(x => x.id == "stp" number) 1]
}