export default function TopNav() {
const ns = 'header';
const { t, i18n } = useTranslation(ns);
const data = getData(i18n.language, ns);
var topNav = [];
const parseData = () => {
data.then((json) => {
const headerArray = mkNumArray(json, 'row1');
var topNav = headerArray.map((i) => {
const url = t("row" + i + ".button" + i + ".url");
const label = t("row" + i + ".button" + i + ".label");
return (
<a href={url}>{label}</a>
);
})
console.log(topNav);
});
};
parseData(topNav);
console.log(topNav);
return(
....
)
}
I’m having trouble figuring out how to handle this nav variable. Because of the async request in getData, I want to have the variable set inside this parseData function, but then want to have it available for returning in the component. The console log inside ParseData is correct, but the one before return is empty. What’s the best way to do this?
There’s some external functions defined here, but I don’t think they are relevant.
>Solution :
You should read useState and useEffect.
The common flow is like this: make topNav a state of your component. its initial value may be empty. after the first time rendering, the parseData is triggered and set value for topNav hence trigger re-rendering your component with new value of topNav.
Your code may resemble below:
export default function TopNav() {
const [topNav, setTopNav] = useState([]);
useEffect(()=>{
const parseData = () => {
data.then((json) => {
// ** do logic...
setTopNav(/*value of topnav*/);
});
};
}, []);
return(
....
)
}