0

I try to get only the name's region in this API link but it shows me errors in the properties of the setState. Syntax problem or something else?

By the way: Why I use this case, map function? For future purposes.

Thanks!

App Js :

import React from 'react';
import './App.css';
import Region from './region';
import {BrowserRouter,Switch,Route} from "react-router-dom";

function App() {
  return (
    <div className="App">
      <BrowserRouter>
        <Switch>
          <Route exact path = "/" component={Region}/>
        </Switch>
      </BrowserRouter>
    </div>
  );
}

export default App;

the component:

import React, { Component } from "react";

class Region extends Component {
    constructor (props) {
        super (props)
        this.state = {
            items:[],
            isLoad:false
        }
    }

    ComponentDidMount () {
        fetch("https://restcountries.eu/rest/v2/region/europe").then(res=>res.json()).then(JSON=> {
            this.setState ({
                isLoad = true,
                items = JSON,
            }) 
        })
    }

    render () {
        let {isLoad,items} = this.state;

        if(!isLoad) {
            return <div>Loading...</div>
        }

        else {
            return <div>
                <ul>
                    {items.map(items=>(
                        <li key={items.name}> </li> 
                    ))}
                </ul>
            </div>
        }
    }
}

export default Region;

json file: https://restcountries.eu/rest/v2/region/europe

1 Answer 1

1

The reason behind .map() is you get an opportunity to manipulate your array elements by accessing each elements and returning a different way, structure. In React case it helps to render proper JSX elements for render() method. Suggested read Lists and Keys from React's official documentation.

Read from Array.prototype.map() documentation:

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

First issue is wrongly passed properties to setState(), please note that I'm using : instead of =. Try to change as the following:

this.setState({
   isLoad: true,
   items: JSON,
});

Additionally you can try the following - you had the same name for current element as the array itself - it just better to have different name:

return <div>
     <ul>
         {items && items.map(e => <li key={e.name}> {e.name} </li>)}
     </ul>
</div>

I hope that helps!

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.