mttetc
mttetc

Reputation: 745

Filtering element in array is not working in Reactjs

I'm trying to make a basic app by fetching data from an API. I'm now trying to filter a value from that data through an array. I'm using react-search-input and getting "TypeError: Cannot read property 'filter' of undefined" and I don't understand why.

What do I need to do to avoid this error ?

Code here :

import React, { Component } from 'react';
import SearchInput, {createFilter} from 'react-search-input'

const API = 'https://swapi.co/api/people/';

class App extends Component {
    constructor(props) {
    super(props);

    this.state = {
      items: [],
      searchTerm: '',
    }
    this.searchUpdated = this.searchUpdated.bind(this)
  }

  componentWillMount() {
    this.fetchData();
  }

  fetchData = async () => {
    const response = await fetch(API);
    const json = await response.json();
    this.setState({ items: json.results })
  }

  render() {
    const items = this.state.items;
    const filteredData = items.results.filter(createFilter(this.state.searchTerm, items.results))

    return (
      <div>
        <SearchInput className="search-input" onChange={this.searchUpdated} />
        <div className="row">
            {filteredData.map((item, i) =>
              <div className="col-md-4" key={i}>
                <a href={item.url}>{item.name}</a>
                <p>Caractéristiques :</p>
                <ul>
                  <li>Année de naissance : {item.birth_year}</li>
                  <li>Taille : {item.height} cm</li>
                  <li>Masse : {item.mass}</li>
                  <li>Couleur des yeux : {item.eye_color}</li>
                  <li>Couleur de cheveux : {item.hair_color}</li>
                  <li>Couleur de peau : {item.skin_color}</li>
                </ul>
              </div>
            )}
        </div>
      </div>
    )
  }
  searchUpdated (term) {
    this.setState({searchTerm: term})
  }
}

export default App;

Upvotes: 0

Views: 70

Answers (2)

jo_va
jo_va

Reputation: 13993

You are trying to access the results property on this.state.items which is declared as an empty array. You should declare items like this:

this.state = {
  items: { results: [] },
  searchTerm: '',
}
...
const items = this.state.items;
items.results.filter(createFilter(this.state.searchTerm, items.results))

or simply declare results as an array and use it:

this.state = {
  results: [],
  searchTerm: '',
}
...
this.state.results.filter(createFilter(this.state.searchTerm, this.state.results))

Upvotes: 1

Jevin Anderson
Jevin Anderson

Reputation: 61

You have a syntax error. You're trying to access a result key on an array.:

// items is an array, arrays don't have keyword result
const filteredData = items.results.filter(createFilter(this.state.searchTerm, items.results)) 

Upvotes: 0

Related Questions