1

I am using React and the Pokemon API (https://pokeapi.co/) to make a simple web app where the user can search pokemons by name and filter by type.

I successfully implemented the searching for my own data.

constructor() {
    super();
    this.state = {

        contactData: [
            { name: 'Abet', phone: '010-0000-0001' },
            { name: 'Betty', phone: '010-0000-0002' },
            { name: 'Charlie', phone: '010-0000-0003' },
            { name: 'David', phone: '010-0000-0004' }
        ]

    };
}

With the contactData that I have, I successfully search the data that contains the keyword.

 render() {

        const mapToComponents = (data) => {
            //data.sort();

            data = data.filter(
                (contact) => {
                    return contact.name.toLowerCase()
                    .indexOf(this.state.keyword.toLowerCase()) > -1;
                }
                )

          return data.map((contact, i) => {
            return (<ContactInfo contact={contact} key={i}/>);
          });
        };

        return(


            <div className="Home">

                <input
                name = "keyword"
                placeholder = "Search"
                value = { this.state.keyword }
                onChange = { this.handleChange }
                />
                <div className="info">{ mapToComponents(this.state.contactData)}</div>

            </div>
        )
    }

My question is, I am not sure how to do the same thing with my response data from the Pokemon API. My response data looks like this in the console:

{count: 811, previous: null, results: Array(20), next: "https://pokeapi.co/api/v2/pokemon/?offset=20"}
count
:
811
next
:
"https://pokeapi.co/api/v2/pokemon/?offset=20"
previous
:
null
results
:
Array(20)
0
:
{url: "https://pokeapi.co/api/v2/pokemon/1/", name: "bulbasaur"}
1
:
{url: "https://pokeapi.co/api/v2/pokemon/2/", name: "ivysaur"}
2
:
{url: "https://pokeapi.co/api/v2/pokemon/3/", name: "venusaur"}
3
:
{url: "https://pokeapi.co/api/v2/pokemon/4/", name: "charmander"}
4
:
{url: "https://pokeapi.co/api/v2/pokemon/5/", name: "charmeleon"}
5
:
{url: "https://pokeapi.co/api/v2/pokemon/6/", name: "charizard"}
6
:
{url: "https://pokeapi.co/api/v2/pokemon/7/", name: "squirtle"}
7
:
{url: "https://pokeapi.co/api/v2/pokemon/8/", name: "wartortle"}
8
:
{url: "https://pokeapi.co/api/v2/pokemon/9/", name: "blastoise"}
9
:
{url: "https://pokeapi.co/api/v2/pokemon/10/", name: "caterpie"}
10
:
{url: "https://pokeapi.co/api/v2/pokemon/11/", name: "metapod"}
11
:
{url: "https://pokeapi.co/api/v2/pokemon/12/", name: "butterfree"}
12
:
{url: "https://pokeapi.co/api/v2/pokemon/13/", name: "weedle"}
13
:
{url: "https://pokeapi.co/api/v2/pokemon/14/", name: "kakuna"}
14
:
{url: "https://pokeapi.co/api/v2/pokemon/15/", name: "beedrill"}
15
:
{url: "https://pokeapi.co/api/v2/pokemon/16/", name: "pidgey"}
16
:
{url: "https://pokeapi.co/api/v2/pokemon/17/", name: "pidgeotto"}
17
:
{url: "https://pokeapi.co/api/v2/pokemon/18/", name: "pidgeot"}
18
:
{url: "https://pokeapi.co/api/v2/pokemon/19/", name: "rattata"}
19
:
{url: "https://pokeapi.co/api/v2/pokemon/20/", name: "raticate"}
length
:
20
__proto__
:
Array(0)
__proto__
:
Object

How can format this like the contactData that I've created and display it for searching?

1 Answer 1

3

First you need one method to fetch data from API like this:

loadData() {
  fetch('https://pokeapi.co/api/v2/pokemon/')
    .then(result => result.json())
    .then(items => this.setState({ data: items })
}

Then create another method componentDidMount and pass loadData():

componentDidMount() {
  this.loadData()
}

From official React documentation:

componentDidMount() is invoked immediately after a component is mounted. Initialization that requires DOM nodes should go here. If you need to load data from a remote endpoint, this is a good place to instantiate the network request. Setting state in this method will trigger a re-rendering.

More information here: React Components

JSFiddle example:

class Data extends React.Component {
    constructor(props) {
    super(props);
      this.state = {
        data: []
      };
  }
  
  componentDidMount() {
     this.loadData()
  }

  // Fetch data from API:
  loadData() {
    fetch(`https://pokeapi.co/api/v2/pokemon/`)
      .then(result => result.json())
      .then(items => this.setState({data: items}))
  }
  
  render() {
  
  const mapToComponents = data => {
    // Your logic...
    // Here you can use data...
  };
    
  return (
    <div>
      <h1>Pokemon's:</h1>
        <ul>
          {this.state.data.results !== undefined ?
           this.state.data.results.map((x, i) => <li key={i}>{x.name}</li>) 
           : <li>Loading...</li>
          }
        </ul>

        <h1>THIS.STATE.DATA:</h1>

        <pre>
          {JSON.stringify(this.state.data, null, 2)}
        </pre>
      </div>
    );
  }
}

ReactDOM.render(
  <Data />,
  document.getElementById('container')
);
<div id="container">
    <!-- This element's contents will be replaced with your component. -->
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

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

Comments

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.