Patrick Hayden
Patrick Hayden

Reputation: 53

Issue with Creating a Search Bar with React

I'm trying to create a search bar that will load a list of user's names from an api when input is added to the search bar and im getting an error. im not quite sure what to make the parameters of the .filter method. or if im even using the correct method. I thought about using lodash _.filter but not sure how or where to implement that. im new to react so keep that in mind! id be very thankful for any suggestions

import React, { Component } from "react";
import ReactDOM from "react-dom";
import './App.css'

class App extends Component {
  constructor() {
    super();
    this.state = {
      people: [],
      search: ''
    };
  }

  componentDidMount() {
    fetch("https://randomuser.me/api/?page=3&results=10&seed=abc")
      .then(results => results.json())
      .then(data => this.setState({ people: data.results }));
  }
  updateSearch(event) {
    this.setState({ search: event.target.value })
  }
  render() {

    let filteredPeople = this.state.people.filter(
      (people) => {
        return people.data.results.indexOf(e.target.value) !== -1;
        //or maybe use .includes
      }

    );
    return (
      <div className="card">
        <div className="firstlast">
          {filteredPeople.map(people => (
            <div id="names">{people.name.first} {people.name.last}</div>
          ))}
        </div>
        <input type="text" value={this.state.search} onChange={this.updateSearch.bind(this)} />
      </div>
    );
  }
}


export default App;

error message:

Error in /~/App.js (43:32) Cannot read property 'results' of undefined

Upvotes: 1

Views: 465

Answers (2)

ravibagul91
ravibagul91

Reputation: 20755

When you type in input, you need to use that value to filter your data,

{ this.state.search !=="" ? this.state.people.filter( people => people.name.first.includes(this.state.search)).map( (people,index) => (
        <p key={index}>{people.name.first} {people.name.last}</p> 
    )) 
    :
    this.state.people.map((people,index) => (
        <p key={index}>{people.name.first} {people.name.last}</p> 
    ))
} 

Demo

Note: I have used key={index} because I didn't find anything unique in your response, but always try to avoid using index as key.

Upvotes: 1

Shmili Breuer
Shmili Breuer

Reputation: 4147

You need to access people.results instead of people.data.results

Cause this.setState({ people: data.results }) adds data.results to people directly.

Upvotes: 0

Related Questions