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

Copying data of one array with transformation into another array in javascript/react

My API is returning below output.

[
    "ANT",
    "ARG",
    "ARM",
    "BUR",
    "UAE"
]

in my array I need to store countryname corresponding to these countrycode.
so for that I have used country-data library in react.
so I can get output like console.log(countries["UAE"].name);
I need to store country name in my countryData array which is declared below.

my react code is.

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

 this.state = {
      countryData: [],
    };

I am using arraycode like below.

updateDropdownData() {
    axios.get(`http://localhost:8080/country_code`).then((res) => {        
      res.data.map((code) => {
        alert(countries[code].name);
        countryData.push.apply(countryData, countries[code].name);
      });
      this.setState({ countryData });
    });
  }

but I am getting error

index.bundle.js:122 Uncaught (in promise) ReferenceError: countryData is not defined
    at index.bundle.js:122:217123
    at Array.map (<anonymous>)

what mistake I am doing. I am quite new in javascript and react.

Edit1:-
alert(countries[res.data[0]].name); //this line is working.

but const _countryData = res.data.map((code) => countries[code].name); giving error.
enter image description here

>Solution :

Changing the state value directly does not fit React’s method.

updateDropdownData() {
    axios.get(`http://localhost:8080/country_code`).then((res) => {
      const _countryData = res.data.map((code) => countries[code].name )        
      this.setState({ countryData: _countryData });
    });
  }

EDIT

The countries variable must be where you run it. And the shape of
the variable should be as follows.

const countries = {
    "ANT" : { name : "ant_name"  },
    "ARG" : { name : "arg_name"  },
    ...
}
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