I am creating a react wizard component, and want to pass data נetween parent and children using contextץ
So I created a wizard, context, provider, and custom hook, but the issue is that if I try to use the context, on the wizard component, it does not show the correct info
(see https://codesandbox.io/embed/wizardwitcontext-rfpui )
How to make it so that I can rely on data in context on the wizard itself so I can transfer the login to the custom hook?
useWizard.js:
import React, { useContext, useEffect } from "react";
import { WizardContext } from "./WizardContext";
const useWizard = () => {
const [state, setState] = useContext(WizardContext);
function setMaxSteps(maxSteps) {
setState(state => ({ ...state, maxSteps }));
}
function moveToStep(index) {
if (state.maxSteps && state.maxSteps > index) {
setState({ ...state, currentStep: index });
return index;
}
return state.currentStep;
}
function back() {
if (state.maxSteps) {
if (state.currentStep > 0) {
setState({ ...state, currentStep: state.currentStep - 1 });
window.scrollTo(0, 0);
}
}
}
//move back a step
function next() {
if (state.currentStep < state.maxSteps) {
setState({ ...state, currentStep: state.currentStep + 1 });
window.scrollTo(0, 0);
}
}
return {
setMaxSteps,
moveToStep,
back,
next,
maxSteps: state.maxSteps,
currentStep: state.currentStep,
state
};
};
export default useWizard;
Wizard.jsx:
const { state, currentStep, back, next, maxSteps, setMaxSteps } = useWizard();
return (
<div className="wizard">
<WizardProvider
maxSteps={React.Children.count(props.children)}
currentStep={0}
>
{/* <div className="wizard__upper">
<ProgressIndicator currentIndex={selected} onChange={onClick}>
{steps}
</ProgressIndicator>
<Button id="wizardCloseBtn" kind="ghost" onClick={onClose}>
<Icon icon={iconHeaderClose} />
</Button>
</div> */}
<div className="wizard__separator" />
<div className="wizard__content">
{`in wizard: cur=${currentStep}, max=${maxSteps}`}
{/* {getContentAt(0)} */}
{stepContentWithProps}
</div>
{/* <div className="wizard__buttons">
{showBack && (
<Link id="back" onClick={back}>
back
</Link>
)}
{showNext && (
<button id="next" onClick={next} kind="secondary">
Next Step
</button>
)}
</div> */}
</WizardProvider>
</div>
);
Step2:
import React, { useState, useContext, useEffect } from "react";
import useWizard from "./useWizard";
function Step2(props) {
const {
currentStep,
moveToStep,
maxSteps,
setMaxSteps,
next,
prev
} = useWizard();
return (
<div>
<p>Step 2</p>
{`in step2 (inner child of wizard): cur=${currentStep} see that cur !== cur from wizard above`}
<br />
<button onClick={() => moveToStep(1)}>
Click me to change current step
</button>
</div>
);
}
export default Step2;
End result is:
in wizard: cur=undefined, max=undefined
p1
in index.js: cur=undefined
Step 2
in step2 (inner child of wizard): cur=0 see that cur !== cur from wizard above