skip to Main Content

the problem is this:

I have a global variable (outside componentA definition) let name: string for example, I need to assign a value after fetch it from backend in the useEffect [], and use it before the component is exported, but at that time the variable is undefined, there is any way to do it or something like that?

this is a code example

import React from 'react'

let name: string

const ComponentA = () => {
 useEffect(() => {
  fetchName()
 }, [])

 const fechName = async () => {
  const _name = await backendService.getName()
  name = _name
 }

 return (
  <>Anything</>
 )
}

console.log("name: ", name) // getting undefined


export default ComponentA

EDIT: The thing is, i am implementing Codepush, and this must be applied when component is exported, like that:
export default CodePush({option: name})(ComponentA), so i want to set that option attribute dinamically, gettting it from backend

2

Answers


  1. It looks like you are assigning name to itself, and since it is undefined, it will always stay undefined. Make sure to assign name to _name instead

     const fechName = async () => {
      const _name = await backendService.getName()
      name = _name
     }
    

    EDIT: BTW, even with this change, you will still see undefined in the console.log because the console.log statement is executed before the name variable is assigned a value inside the fetchName function. Try moving the console.log into fetchName after the name assignment.

    Login or Signup to reply.
  2. It seems like it is a XY problem, the point should be how to create component dynamically, you can do something like this:

    export async function createComponentA() {
        const name = await getOptionName()
    
        return CodePush({option: name})(ComponentA)
    }
    

    the returned component may need a useMemo to avoid re-fetch too many times

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search