0

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.

 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

3
  • 1
    How about declaring it then before the mapping task starts? Commented Jan 20, 2022 at 12:32
  • 1
    And did the OP ever asks him/herself what countryData.push.apply(countryData, countries[code].name); is good for? Doesn't the OP not just want to directly map countries[code].name into the (before declared) countryData array? Commented Jan 20, 2022 at 12:36
  • Thank you Peter. Now I am getting one weird error. I have edited the question and put in the end. Could you please check? Commented Jan 20, 2022 at 13:48

1 Answer 1

1

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"  },
    ...
}
Sign up to request clarification or add additional context in comments.

3 Comments

ofcourse...Hong. actually this is giving one minor error. could you please check. I have edited the question.
@Oze I added an answer.
Thanks hong. what i need to change in my main code? I imported library like import { countries } from 'country-data';

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.