Skip to content

Instantly share code, notes, and snippets.

@enriquebeta6
Created October 7, 2022 15:34
Show Gist options
  • Save enriquebeta6/bd82a6f00a44d6d8b1bc968edc702154 to your computer and use it in GitHub Desktop.
Save enriquebeta6/bd82a6f00a44d6d8b1bc968edc702154 to your computer and use it in GitHub Desktop.
This HOC is a util that can be use with this app https://github.com/vtex-apps/checkout-button-example
/* eslint-disable @typescript-eslint/explicit-member-accessibility */
/* eslint-disable import/order */
// Dependencies
import React from 'react'
type OrderForm = any
interface StateProviderState {
orderForm: OrderForm | null
}
type StateProviderProps = Record<string, unknown>
const initialState: StateProviderState = {
orderForm: null,
}
export default function withOrderForm(
WrappedComponent: React.ComponentClass<any>
) {
return class StateProvider extends React.Component<
StateProviderProps,
StateProviderState
> {
private timeoutID: ReturnType<typeof setTimeout> | null
constructor(props: StateProviderProps) {
super(props)
this.timeoutID = null
this.state = initialState
}
setOrderForm = (_: unknown, orderForm: OrderForm) => {
if (this.timeoutID) clearTimeout(this.timeoutID)
this.timeoutID = setTimeout(() => {
this.setState(prevState => ({
...prevState,
orderForm,
}))
}, 500)
}
componentDidMount() {
if (window.vtexjs.checkout.orderForm) {
this.setOrderForm(null, window.vtexjs.checkout.orderForm)
}
$(window).on('orderFormUpdated.vtex', this.setOrderForm)
}
componentWillUnmount() {
$(window).off('orderFormUpdated.vtex', this.setOrderForm)
}
render() {
return <WrappedComponent orderForm={this.state.orderForm} />
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment