react-async-script icon indicating copy to clipboard operation
react-async-script copied to clipboard

Setting component to rerender when script loaded

Open krrishdholakia opened this issue 5 years ago • 2 comments

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;

krrishdholakia avatar Jan 22 '20 17:01 krrishdholakia

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

sephi-dev avatar Jan 23 '20 15:01 sephi-dev

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

sephi-dev avatar Jan 23 '20 16:01 sephi-dev