I need to display users public name via reactjs as per {publicName}
OR {pubname}
but it throws error, publicName is not defined
Here is my Code:
import React, { useEffect, useState, Fragment } from "react";
const fetchAccountId = async () => {
const publicName = "Nancy Moore";
return publicName;
};
function App() {
const [accounts] = useState(fetchAccountId);
fetchAccountId();
const [pubname, setPubname] = useState(null);
setPubname(publicName);
useEffect(() => {}, []);
return (
<div>
<h2> Display Public Name</h2>
<div>
{publicName}
OR {pubname}{" "}
</div>
</div>
);
}
export default App;
2
Answers
Since there is no such
publicName
defined in thescope
and thus error.There are following issues in your code snippet:
publicName
defined in the scope to access it.Better to use
useEffect
and set state in it. So that it will set state only if it is required.You can also use
async-await
if you prefer to use it:CODESANDBOX
Just need on adjustment, add change
with
and it would be better if you use it in
useEffect()
.This use effect function will trigger when component is loaded.
Note: the
const publicName
infetchAccountId()
is not a global variable it only exists within thefetchAccountId()
function.