Created
October 7, 2022 15:34
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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