dozoisch / react-async-script

A React composition mixin for loading 3rd party scripts asynchronously
MIT License
177 stars 29 forks source link

Setting component to rerender when script loaded #50

Open krrishdholakia opened 4 years ago

krrishdholakia commented 4 years ago

Currently I have a component: QuickAdd that needs the google autocomplete api to run

However, while the component renders, it doesn't seem like the autocomplete has finished loading. If i go to another component and then return to the QuickAdd component then it works, which makes me think it needs to rerender after the script is loaded.

The globalName is always passed as a prop and but is always undefined. What other listener can i use for this?

const callbackName = "onloadcallback"; const globalName = "quickAddLoader"; const url =https://maps.googleapis.com/maps/api/js?key=API_KEY&libraries=places; const AsyncHoc = makeAsyncScriptLoader(url, {globalName: globalName})(QuickAdd); export default AsyncHoc;

sephi-dev commented 4 years ago

I have the exact same issue, would be glad on finding a solution

sephi-dev commented 4 years ago

Ok so I found a way to make it worked properly I guess. Here's what I did :

in the parent of my AsyncComponent

import Geosuggest from "@components/geosuggest";

const Component = () => {
  const [geosuggestActive, setActive] = useState(false);
  const GOOGLE_URL = `https://maps.googleapis.com/maps/api/js?key=${process.env.REACT_APP_GOOGLE_KEY}&libraries=places`;
  const AsyncGeosuggest = makeAsyncScriptLoader(GOOGLE_URL, { globalName: "google" })(
    Geosuggest,
  );

  return (
    <AsyncGeosuggest
      asyncScriptOnLoad={() => setActive(true)} // the important props for the callback
      isActive={geosuggestActive} // just pass the state, and display a placeholder instead nothing when not loaded
    />
  );
}

Hope It will help you