Skip to content

Commit

Permalink
Add react example
Browse files Browse the repository at this point in the history
  • Loading branch information
timomeh committed Mar 4, 2024
1 parent 73b144c commit d9e5e19
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 0 deletions.
69 changes: 69 additions & 0 deletions docs/porting-embed.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ embed.on('completed', ({ porting }) => {
- [Using a different form id](#using-a-different-form-id)
- [Updating options](#updating-options)
- [Unmount the embed](#unmount-the-embed)
- [Usage with React](#usage-with-react)
- [Reference](#reference)
- [Initializing the Porting Embed](#initializing-the-porting-embed)
- [`connectSession`](#connectsession)
Expand Down Expand Up @@ -287,6 +288,74 @@ app.onBackNavigation(() => {
See also:
- [`embed.unmount()`](#embedunmount)

### Usage with React

```js
export function App() {
const $mount = useRef<HTMLDivElement>(null)
const [status, setStatus] = useState('initializing')
const [step, setStep] = useState(null)
const [embed, setEmbed] = useState<PortingEmbedInstance>()

useEffect(() => {
async function main() {
const session = await fetch('/connectSessionForCurrentPorting')
.then(res => res.json())

const embed = await PortingEmbed(session)
setEmbed(embed)
}

main()
}, [])

useEffect(() => {
if (!embed) return

setStatus('loaded')
setStep(embed.currentStep())
embed.mount($mount.current)

const handleStepChange = ({ nextStep }) => setStep(nextStep)
const handleCompleted = ({ porting }) => {
router.push(`/completed?porting=${porting.id}`)
}
const handleSubmitStatus = ({ status }) => {
if (status === 'loading') {
setStatus('submitting')
} else {
setStatus('loading')
}
}

embed.on('stepChange', handleStepChange)
embed.on('completed', handleCompleted)
embed.on('submitStatus', handleSubmitStatus)

return () => {
embed.off('stepChange', handleStepChange)
embed.off('completed', handleCompleted)
embed.off('submitStatus', handleSubmitStatus)
embed.unmount()
}
}, [embed])

return (
<>
<StepTitle step={step} />
{status === 'initializing' && <Loading />}
<div ref={$mount} />
<Button
form="gigsPortingEmbedForm"
loading={status === 'submitting'}
>
Submit
</button>
<>
)
}
```

## Reference

### Initializing the Porting Embed
Expand Down
2 changes: 2 additions & 0 deletions lib/PortingEmbed/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@ type Events = {
stepChange: StepChangeEvent
}

export type PortingEmbedInstance = Awaited<ReturnType<typeof PortingEmbed>>

/**
* Initializes an embed to complete a porting (port-in a number). Requires an
* authenticated ConnectSession. After initialization, the embed can be mounted
Expand Down

0 comments on commit d9e5e19

Please sign in to comment.