JS-201-ReactFundamentals
  • Part 0: App Overview
  • Part 1: Intro to React
    • 1.0: Packages Setup
    • 1.1: Project Setup
    • 1.2: React Router Dom
  • Part 2: JavaScript Concepts
    • 2.0: ES6 Overview
    • 2.1: classes
    • 2.2: constructors
    • 2.3: extends
    • 2.4: super
    • 2.5: interpolation
    • 2.6: map
    • 2.7: filter
  • Part 3: Functional Components
    • 3.0: Functional Components Overview
    • 3.1: Calling Functional Components
    • 3.2: Single Element Rule
    • 3.3: Arrow Functions
    • 3.4: Challenge
    • 3.4: Solution
    • 3.5: Challenge 2
    • 3.5: Solution 2
  • Part 4: JSX Challenge
    • 4.1: JSX Overview
    • 4.1: Challenge Answer
    • 4.2: className
  • Part 5: Class Concepts
    • 5.1: State
    • 5.2: setState
    • 5.3: Class Components Challenge
    • 5.4: Class Components Challenge Answer
  • Part 6: Props Starter
    • 6.0: Props Overview
    • 6.1: Props Demo and Challenge 1
    • 6.2: Props Answer 2
    • 6.3: Props Passing Functions and Challenge 2
    • 6.4: Props Answer 2
    • 6.5: External Props and Mapping Components
    • 6.6: PropTypes
  • Part 7: Lifecycle Methods
    • 7.0: Lifecycle Overview
    • 7.1: Lifecycle Methods
    • 7.2: Mounting Methods
    • 7.3: Update Methods
    • 7.4: Unmount Methods
  • Part 8: Apps
    • 1.0 - Small Timer Apps
      • 1.1 - Simple Timer
      • 1.2 - Clock App
      • 1.3 - Stop Watch App
      • 1.4 - Challenge
    • 2.0 - Concept List
      • 2.1 - Concept Data
      • 2.2 - Concept App Component
      • 2.3 - Concept Component
      • 2.4 - Concept List Component
    • 3.0 - NYT
      • 3.1 - NytApp Component
      • 3.2 - Nyt Results
    • 4.0 - The Friend List App
      • 4.1 - Friend List App Component
      • 4.2 - Friend Component
    • 5.0 - Movie Search Application
      • 5.1 - Form Component
      • 5.2 - Form Results Component
      • 5.3 - Styled Components
    • 6.0 - YouTube Api
      • 6.1 - Video Component
      • 6.2 - Video Component
      • 6.3 - Video Component
    • 7.0 - Github Api Application
      • 7.1 - The Users
      • 7.2 - Github API Component
      • 7.3 - Github API Card
      • 7.4 - Github API Card Form
      • 7.5 - Github API Card List
      • 7.6 - Github API Search
      • 7.7 - Github API Challenge
    • 8.0 - Bitcoin Api Application
      • 8.1 - Bitcoin API Setup
      • 8.2 - Bitcoin API Fetch
      • 8.3 - Bitcoin API Line Chart
      • 8.4 - Bitcoin API Fetching Data
      • 8.5 - Bitcoin API Info Box
      • 8.6 - Bitcoin API Completed Code
    • 9.0 - Google Maps Api Challenge
    • 10.0 - Sound Cloud App Challenge
    • 11.0 - VR App Challenge
    • 12.0 - React Native Intro
  • Part 9: Project
  • Part 10: Notes
    • 10.1 - Resources
    • 10.2 - Troubleshooting
Powered by GitBook
On this page
  • state
  • render()
  • handleKeyUp
  • Pointing to the API
  • Steps to Getting an API Key
  • then()
  • Error Handling
  • preventDefault()
  • Form.js
  1. Part 8: Apps
  2. 5.0 - Movie Search Application

5.1 - Form Component

In the last section, we set up our movie app, but now we need to create our next component Form. This component will be where we accept user input, query the API based on that user input, and then send the results to another component to display.

Let's just get started by setting up our component and make sure that it's displaying in our app. First, go into Form.js. Then type the following code into it:

import React, { Component } from 'react';

export class Form extends Component {
    render() {
        return (
            <h1> This is a form </h1>
        );
    }
}

Now you should see "This is a form" in your app.

state

Next thing we need to do is think about our state structure. What kind of state do we need, what information do we need to keep track of? All we're wanting to do here is have the user type into an input field and get results based on that input. It makes sense to have the results in the state, but really that's about it. Let's go ahead and set up our constructor in our Form. Notice how we're setting up the state to hold the results here. Go ahead and type the following in your Form component.

 constructor(props) {
        super(props);
        this.state = {
            results: []
        }
    }

render()

So now that we've got our state set up, we can think about what we're going to need to GET those results. We need an input for the user to type in and then some actions to occur when that happens to go get information from an API. Let's think about what we need to render to the screen. You can take your h1 out of the render and instead put in a form to capture their input. All that really needs to be in this form, is an input. This input should do something when they type, we can use onKeyUp for this.

Additionally, if they try and submit the form somehow, we need to make sure we're preventing the default action of the form, just like always. Go ahead and type the following code in your render.

    render() {
        return (
            <form onSubmit={this.handleSubmit} id="form">
                <input onKeyUp={this.handleKeyUp} id="searchInput" className="searchBar" type="text" placeholder="Search a movie" required />
            </form>
        );
    }

Notice that we've called our two methods handleSubmit and handleKeyUp. It's convention to use handleSubmit for form submission and handle in general when dealing with user input. Now that we have these methods, we need to define them!

handleKeyUp

Now that our render can use these methods, we need to actually make them do things. Let's first start with handleKeyUp. When someone types or "keys up", we want it to hit our api. We want to be able to give them suggestions based on what they're typing in. So, for example, if they can't quite remember the movie name, but know it starts with "hidden", then they'll see a list of responses based on "hidden". Let's go ahead and create our method, and comment out some of the things that we want to actually happen in this method.

handleKeyUp = (e) => {
 // capture user's input from event

 // use user's input to hit an api to get movies

 // store the results of our api query in our state

 // we also need to handle errors
}

Make sure you understand what we're trying to do here. Every time a user types anything in, we're going to hit the api and see what movies match what they've typed. Then, we're going to store the results in our state. We also need to handle errors so they don't break our application.

Pointing to the API

The first step is to hit our API, and pass in useful info such as the value the user typed in. For this project we are using The Movie DB API, so before we can even set up how to get there, we need to go check out the docs. As with most open APIs, there are rate limits on this API, so you always want to have a unique key for your application, that no one else can use, so you can use all of your own API requests within your limit.

Steps to Getting an API Key

  1. Email verify and sign in to your account.

  2. Click on your settings on your account.

  3. Click the API button on the menu

  4. Click Create

  5. Click "Developer"

  6. Accept the terms of use at the bottom.

  7. Call your application anything you want. You can use it to indicate that you're learning. Similarly, for application URL you can put localhost for now. Fill out the rest of the information. You can use pseudo-information, if you'd like.

  8. Now you should see your key. You can grab the v3 auth version.

Now that we have our API key, we're ready to move on to hitting the API.

The first thing we need to do is set our API key up in a const variable. We use const because this won't change.

 // use user's input to hit an api to get movies
 // store the results of our api query in our state
 // we also need to handle errors

const key = 'yourKeyHere';
// capture user's input
 // use user's input to hit an api to get movies
 // store the results of our api query in our state
 // we also need to handle errors

const key = 'yourKeyHere';
fetch(`https://api.themoviedb.org/3/search/movie?api_key=${key}&language=en-US&query=${e.target.value}&page=1&include_adult=false`)

then()

Next, just like ajax calls, we can do things with the results of our query, and we need to, to take the results and put them in the state. So, in our then we can grab the results and set our state with them.

// capture user's input
 // use user's input to hit an api to get movies
 // store the results of our api query in our state
 // we also need to handle errors

const key = 'yourKeyHere';
fetch(`https://api.themoviedb.org/3/search/movie?api_key=${key}&language=en-US&query=${e.target.value}&page=1&include_adult=false`)
    .then(response => {
        response.json().then(data => {
            const results = data.results;
            this.setState({ results });
        });
    })

Error Handling

So, now that it works on successful responses, we also need to handle errors. We shouldn't try and set state if the API doesn't respond correctly. Our whole handleKeyUp() should look like this. We're console logging our errors so that we can see and fix them.

        const key = 'yourKeyHere';

        fetch(`https://api.themoviedb.org/3/search/movie?api_key=${key}&language=en-US&query=${e.target.value}&page=1&include_adult=false`)
            .then(response => {
                if (response.status !== 200) {
                    console.log('Error: ' + response.status);
                    return;
                }

                response.json().then(data => {
                    const results = data.results;
                    this.setState({ results });
                });
            })

            .catch(err => {
                console.log('Fetch Error :-S', err);
            })
    }

preventDefault()

Now that we've set up our handle key up to handle all the API requests, we just need to prevent the default action of the form submit from happening. We don't need anything in particular to happen there, so we want to preventDefault, just like we have previously. Type this method out just below your constructor and above handleKeyUp().

 handleSubmit = (e) => {
        e.preventDefault();
    }

Form.js

Your complete Form component should look like the following block of code.

import React, { Component } from 'react';

export class Form extends Component {
    constructor(props) {
        super(props);
        this.state = {
            results: []
        }
 }

    handleSubmit = (e) => {
        e.preventDefault();
    }

    handleKeyUp = (e) => {
        const key = 'thisIsAKeyButNotARealOne';

        fetch(`https://api.themoviedb.org/3/search/movie?api_key=${key}&language=en-US&query=${e.target.value}&page=1&include_adult=false`)
            .then(response => {
                if (response.status !== 200) {
                    console.log('Error: ' + response.status);
                    return;
                }

                response.json().then(data => {
                    const results = data.results;
                    this.setState({ results });
                });
            })

            .catch(err => {
                console.log('Fetch Error :-S', err);
            })
    }

    render() {
        return (
            <form onSubmit={this.handleSubmit} id="form">
                <input onKeyUp={this.handleKeyUp} id="searchInput" className="searchBar" type="text" placeholder="Search a movie" required />
            </form>
        );
    }
}

In our next part, we'll create our FormResults component.

Previous5.0 - Movie Search ApplicationNext5.2 - Form Results Component

Last updated 7 years ago

Sign up for an account .

Next, we need to actually use this to hit the API. To figure out how to do this, it's a good idea to look at the documentation to see how to format your requests. All APIs should have documentation letting you know how to do this, as no one just magically understands the format of someone else's API. Since we're wanting to search movies, we can look at that section of the api. . Check out the API Docs to understand how this works.

We're going to use fetch to hit our API. are the docs for using fetch. While you don't need to go delve into the fetch documentation right at the moment, at some point, it's not a bad idea to go read. You can learn a lot about fetch within the context of what we're about to do. Let's set up our request with fetch first.

here
API Docs Here
Here
Movie Form Results Component