Skip to content

Instantly share code, notes, and snippets.

@createdbymahmood
Created July 26, 2021 16:07
Show Gist options
  • Save createdbymahmood/1babead2b6f4fa95e9a3fd69077c3ec8 to your computer and use it in GitHub Desktop.
Save createdbymahmood/1babead2b6f4fa95e9a3fd69077c3ec8 to your computer and use it in GitHub Desktop.
Building a form wizard on top of my route implementation approach
import { useHistory, useRouteMatch } from 'react-router-dom';
import {
StateMachineProvider,
createStore,
useStateMachine,
} from 'little-state-machine';
import { RouteFactory, Route } from 'services/router/RouteFactory';
import { useForm } from 'react-hook-form';
function updateAction(state, payload) {
return {
...payload,
};
}
function Step1() {
const { actions, state } = useStateMachine({ updateAction });
const { register, handleSubmit } = useForm<{
firstName: string;
lastName: string;
}>({
defaultValues: state,
});
const history = useHistory();
const onSubmit = data => {
actions.updateAction(data);
history.push('/home/second-step');
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register('firstName')} />
<input {...register('lastName')} />
<input type="submit" />
</form>
);
}
function Step2() {
console.log('SALAM');
return <div>Second Step</div>;
}
function Result() {
return <div>Third Step</div>;
}
createStore({
data: {
firstName: '',
lastName: '',
},
});
export default function App() {
const match = useRouteMatch();
const ROUTES_ARRAY: Route[] = [
{
path: match.path,
component: Step1,
exact: true,
config: {
private: false,
},
},
{
path: match.path + '/second-step',
component: Step2,
exact: false,
config: {
private: false,
},
},
{
path: match.path + '/result',
component: Result,
exact: false,
config: {
private: false,
},
},
];
return (
<StateMachineProvider>
<RouteFactory routes={ROUTES_ARRAY} />
</StateMachineProvider>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment