Reputation: 331
I want to run a JS function from a module that loaded asynchronously (that exposed by module federation) and to use the return value in a React component.
For example, setting the visibility of some element by the value of a function that returns a boolean value.
All of the examples that I found, explain how to lazy load React components
Thanks! Shlomi
Upvotes: 4
Views: 3809
Reputation: 13651
If you only need to run the function once when the component first loads, you can simply do so using, for example a useEffect()
hook and then set some state. For example
function MyComponent(){
const [someValue, setSomeValue] = useState()
useEffect( () => {
import('someRemote/module').then( module => {
const valueFromFunction = module.myFunction()
setSomeValue(valueFromFunction)
})
})
return someValue != undefined ? <div>The value is {someValue}</div> : <></>
}
Upvotes: 2