'How to create wrapper around asynchronous loaded library
I'm using React and try to import some library that requires me to await it before I can start to use it. Something like this:
import theLibrary from ...
const myApp = () => {
(async () => {
await theLibrary.start
const library = theLibrary
const bla = library.methods.genBla()
// ...
})()
// ...
}
I use this library somewhat often and I want to make a wrapper around it, so I won't get any delay on waiting for it to start all the time, but I don't know how I can achieve it. I would like to know what are the possible ways(OOP/FP) to do it and what is the best one in your opinion.
I want(perhaps you have better alternative?) to use it like this in my components:
import libWrapper from ...
const myApp = () => {
const bla = libWrapper.methods.genBla()
// ...
}
Solution 1:[1]
You could use a hook like:
async function getBlaLib() {
await theLibrary.start
const library = theLibrary
const bla = library.methods.genBla()
return bla
}
function useBlaLib() {
const [bla, setBla] = React.useState();
const [loading, setLoading] = React.useState(false);
React.useEffect(() => {
setLoading(true)
getBlaLib().then(bla => {
setBla(bla)
setLoading(false)
})
}, [])
return [bla, loading]
}
Here is a more complete example: https://codesandbox.io/s/friendly-smoke-sguk21
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Njuguna Mureithi |
