0

I want to dynamically import a react js module. The module is not component it is an object of data, so I cannot use react code splitting. In the webpack docs there is an example with a promise. When I use it like that in a react component, it throws an error because the component tries to render before the promise hadd been resolved. I want to import it in that way in case the data does not exist, I could provide default data.

const dataProps = import(`./dataObject.js`).then(data=> data);

...
 render() {
  <SomeComponente data={data} />
}

1 Answer 1

1

I think the best way to do this is something like:

const dataProps = import(`./dataObject.js`); // Start the importing 

class MyComponent extends React.Component {

    constructor(props) {
        super(props);
        this.state {
            data: null
        }
    }

    componentDidMount() {
        dataProps.then(data => this.setState({ data });
    }

    render() {
       if (this.state.data !== null) {
           return <SomeComponent data={this.state.data} />
       }
       return null;
    }
}

This way when the import is done only then will you actually render anything

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

1 Comment

Thank you, I tried it, but although provinding a catch bock it throws an error, causing the app to crash: Module not found: Can't resolve '

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.