Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to modify variable in function call in functional React component

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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(
     ....
  )
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading