1 | declare var require: any;
|
2 | import * as React from 'react';
|
3 |
|
4 | // create empty context as default
|
5 | const RequestContext = React.createContext({});
|
6 |
|
7 | interface AttachRequestProps {
|
8 | request?: any
|
9 | }
|
10 | /**
|
11 | * This HOC attaches the req sent to the server down to the Components - on server side only, of course!
|
12 | *
|
13 | * see hocs with context: https://itnext.io/combining-hocs-with-the-new-reacts-context-api-9d3617dccf0b
|
14 | *
|
15 | * When using the req: either check whether it is undefined or whether we run on the server -->
|
16 | * how to check whether running on server or in browser: https://www.npmjs.com/package/exenv
|
17 | */
|
18 | const AttachRequest: React.SFC<AttachRequestProps> = (props) => {
|
19 |
|
20 | //console.log("attached request: " , props.request);
|
21 | return <RequestContext.Provider value={props.request}>{props.children}</RequestContext.Provider>
|
22 |
|
23 |
|
24 | };
|
25 |
|
26 | /**
|
27 | * Pass the information on whether the user `isLoggedIn` as prop to the component
|
28 | * @param Component
|
29 | * @returns {function(any): any}
|
30 | */
|
31 | export function withRequest(Component) {
|
32 |
|
33 |
|
34 | return function WrapperComponent(props) {
|
35 | return (
|
36 | <RequestContext.Consumer>
|
37 | {value => {
|
38 | //console.log("with request: ", value);
|
39 | return <Component {...props} request={value} />
|
40 | }}
|
41 | </RequestContext.Consumer>
|
42 | );
|
43 | };
|
44 | }
|
45 |
|
46 | export default AttachRequest;
|
47 |
|
48 |
|
49 |
|
50 |
|