Skip to content

Instantly share code, notes, and snippets.

@ttamminen
Last active June 8, 2020 06:16
Show Gist options
  • Save ttamminen/ccac7b936cce19f35d31b67fa0ea6347 to your computer and use it in GitHub Desktop.
Save ttamminen/ccac7b936cce19f35d31b67fa0ea6347 to your computer and use it in GitHub Desktop.
React HOC that provides Anti-Forgery Token to the React component
import * as React from 'react'
import { connect } from 'react-redux'
//
// Higher order component (HOC) to provide Anti-Forgery Token
// to a component that needs to send POST request to a back-end
// controller action that has an attribute [ValidateAntiForgeryTokenHeader]
//
export function AntiForgeryTokenized<P extends WithToken>(
Comp: React.ComponentClass<P> | React.StatelessComponent<P>
): React.ComponentClass<P> {
class WrappedComponent extends React.Component<
P & { dispatch?: ({}) => void }
> {
public render() {
return <Comp {...this.props} />
}
}
const mapStateToProps = (state: { settings: AppSettings }, props):P => ({
...props,
token: state.settings.antiForgeryToken
})
return connect<P, P, any>(mapStateToProps)(WrappedComponent)
}
export default AntiForgeryTokenized
```
export interface WithToken {
token: string
}
export interface AppSettings {
antiForgeryToken: string
}
@iplus26
Copy link

iplus26 commented Mar 9, 2018

Nice example to explain how to write a HOC in TS 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment