3

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

1
  • 1
    Show what has already been done. lazy load only for react components, not for funcions Commented Dec 28, 2020 at 18:58

2 Answers 2

2

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> : <></>
}
Sign up to request clarification or add additional context in comments.

Comments

-1

export async function calculateMeanDeviation(args: number[]) {
 const sharedFunction = await import('my-shared-library').then(lib => lib.functionName)
 ...
 const results = sharedFunction(args)
 ....
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.