GET request in React.js to a server

Viewed 24652

I have a SearchBar and a Profile component and I want to make a GET request to the server: http://awesomeserver/users. The data in the server are in an array of objects. I want to be able to type in a username in the search bar and when I click "Search", I want to display that user's first name, last name, and email on the page. For example, when I search for jsmith, I want to display: First Name: John, Last Name: Smith, email: jsmith@gmail.com. In order to do that, I need to pass them as props to the Profile component. I am using axios to make the request, but I think I am not using it correctly. How do I search by username, but only retrieve the first name, last name, and email?

This is what a sample data would look like in the server:

{
  username: jsmith,
  firstName: John,
  lastName: Smith,
  email: jsmith@gmail.com,
  hobby: hiking,
  id: 1
}

This is my code so far:

//Profile Component

import React, { Component } from 'react';


class Profile extends Component {
  render() {
    return (
        <div>
            <div>First Name: {this.props.firstName}</div>
            <div>Last Name: {this.props.lastName}</div>
            <div>Email: {this.props.email}</div>
        </div>
    );
  }
}

export default Profile;



//SearchBar component

import React, { Component } from 'react';
import axios from 'axios';

import Profile from './Profile';

class SearchBar extends Component {

  constructor(props) {
  super(props);
  this.state = {
    fetchUser: {
      username: '',
      firstName: '',
      lastName: '',
      email: '',
      hobby: ''
    }
  }
  this.fetchUser = this.fetchUser.bind(this);
}


 fetchUser() {
    var id = this.refs.id.value;

    axios.get('http://awesomeserver/users/${id}')
      .then(resp => resp.json()) 
      .then( (response) => {
        console.log(response);
        this.setState({
          fetchUser: response.data
        });
      })
      .catch( (error) => {
        console.log(error);
      });  
  }

  render() {
    return (
      <div>
          <input ref="id" placeholder="Enter in a username" />
          <button onClick={this.fetchUser}>Search</button>
          <Profile firstName={this.fetchUser.firstName} lastName={this.fetchUser.lastName} email={this.fetchUser.email} />
      </div>
    );
  }
}

export default SearchBar;
3 Answers
Related