2

Now i am trying to fatching data from API using axios and React JS. But when i use this code i got this error:

TypeError: this.state.countries.map is not a function

I have state data:[] and I am trying to set the values of URL in the state. So my code like this:

//get user token
const GetTokens = 'Bearer '.concat(localStorage.getItem('token'));
export default class Index extends Component {
constructor(props) {
    super(props);
    this.state = {
        error: null,
        countries: [],
        response: {}
    }
 }
   componentDidMount() {
    axios.get(apiUrl + '/country-lists', { headers: { Authorization: GetTokens } })
        .then(response => response.data).then(
            (result) => {
                this.setState({
                    countries: result
                });
            },
            (error) => {
                this.setState({ error });
            }
        )
}

And in my render like this:

{this.state.countries.map(list => (
{list.name}
 ))}

Also i tried like this.

render() {
    const (countries ) = this.state
    const (countries = []) = this.state

In my opinion, I made no mistake while getting a token and referencing the map. But I can't figure out where I made the mistake.

R. Richards
  • 24,603
  • 10
  • 64
  • 64
Oktam Yaqubov
  • 113
  • 12

1 Answers1

1

By looking at your console.log I think you should use result.data

 componentDidMount() {
    axios.get(apiUrl + '/country-lists', { headers: { Authorization: GetTokens } })
        .then(response => response.data).then(
            (result) => {
                this.setState({
                    countries: result.data
                });
            },
            (error) => {
                this.setState({ error });
            }
        )
Tony Ngo
  • 19,166
  • 4
  • 38
  • 60