File size: 1,374 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import { Component } from 'react';
import PropTypes from 'prop-types';

class GoogleMapsLoader extends Component {
  static propTypes = {
    apiKey: PropTypes.string.isRequired,
    children: PropTypes.func.isRequired,
    endpoint: PropTypes.string,
  };

  static defaultProps = {
    endpoint: 'https://maps.googleapis.com/maps/api/js?v=quarterly',
  };

  state = {
    google: null,
  };

  isUnmounting = false;

  componentDidMount() {
    // Inline the import to avoid to run the module on the server (rely on `document`)
    // Under the hood we use `dynamic-import-node` to transpile the `import` to `require`
    // see: https://github.com/algolia/react-instantsearch/issues/1425
    return import('scriptjs').then(({ default: injectScript }) => {
      const { apiKey, endpoint } = this.props;
      const operator = endpoint.indexOf('?') !== -1 ? '&' : '?';
      const endpointWithCredentials = `${endpoint}${operator}key=${apiKey}`;

      injectScript(endpointWithCredentials, () => {
        if (!this.isUnmounting) {
          this.setState(() => ({
            google: window.google,
          }));
        }
      });
    });
  }

  componentWillUnmount() {
    this.isUnmounting = true;
  }

  render() {
    if (!this.state.google) {
      return null;
    }

    return this.props.children(this.state.google);
  }
}

export default GoogleMapsLoader;