1

My react web app has a page component. The page component does the async calls for the child components. Now I have to this on every page

export default class Page extends React.Component {

constructor(props) {
    super(props);

    this.state = {
        loading: true
    }
}


componentWillMount = async () => {
    // ... do calls 

    this.setState({
        loading: false
    })
}


render () {
    if (this.state.loading) {
        return <Loading/>
    } else {
        return (
            // Some other components that needs the information from the calls 
        )
    }

}
}

Is there a way to have less boilerplate? I was looking at Higher Order Components with ReactJS. I thought maybe a component that would get a function of the calls needed to be made and a component that renders the function.

const loader = (calls) => (WrappedComponent) => {
    return class Loader extends React.Component {

        constructor (props) {
            super(props);
            this.state = {
                loading: true
            }
        }

        componentWillMount = () => {
            // execute calls function
        };

        render () {
            return this.state.loading ? <Loading/> : <WrappedComponent {... this.props }/>
        }
    }

};

export default loader;

But I haven't figured out a way to pass a calls function into the loader function.

1 Answer 1

1

Sure you can do it using a HOC.

Let's say your function is something along the lines of

const yourFunction = () => {
  return 'A value';
}

Then you can simply pass it to your HOC as a second parameter:

const loader = (WrappedComponent, someFunction) => {
    return class Loader extends React.Component {

        constructor (props) {
            super(props);
            this.state = {
                loading: true,
                value: '',
            }
        }

        componentWillMount = () => {
            // execute the function you passed it
            this.setState({value: yourFunction()});
        };

        render () {
            const { loading, value } = this.state;
            return loading ? <Loading/> : <WrappedComponent value={value} />
        }
    }

};

Then wrap your component with it:

const EnhancedComponent = Loader(WrappedComponent, yourFunction);

Alternatively, you can wrap your HOC in another HOC to pass in stuff like that..

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, I will try that. Didn't think a HOC was so easy.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.