Last active
June 8, 2020 06:16
-
-
Save ttamminen/ccac7b936cce19f35d31b67fa0ea6347 to your computer and use it in GitHub Desktop.
React HOC that provides Anti-Forgery Token to the React component
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
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 | |
``` |
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
export interface WithToken { | |
token: string | |
} | |
export interface AppSettings { | |
antiForgeryToken: string | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice example to explain how to write a HOC in TS 👍