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
It looks like you are assigning
name
to itself, and since it isundefined
, it will always stay undefined. Make sure to assignname
to_name
insteadEDIT: 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 thefetchName
function. Try moving the console.log intofetchName
after thename
assignment.It seems like it is a XY problem, the point should be how to create component dynamically, you can do something like this:
the returned component may need a
useMemo
to avoid re-fetch too many times