Creating the MoviesList Component
Let's learn how to create a component that renders data retrieved from the backend.
In this lesson, we’ll implement the MoviesList
component to consume the functionality in MovieDataService
. These components aim to render views supported by application logic for a smoother user experience. They don’t fetch data from the backend but instead delegate these tasks to services. Some previously created code files have been provided below as a starting point:
import axios from "axios"; class MovieDataService{ getAll(page = 0){ return axios.get(`{{EDUCATIVE_LIVE_VM_URL}}:3000/api/v1/movies?page=${page}`) } get(id){ return axios.get(`{{EDUCATIVE_LIVE_VM_URL}}:3000/api/v1/movies/id/${id}`) } find(query, by = "title", page = 0){ return axios.get(`{{EDUCATIVE_LIVE_VM_URL}}:3000/api/v1/movies?${by}=${query}&page=${page}`) } createReview(data){ return axios.post("{{EDUCATIVE_LIVE_VM_URL}}:3000/api/v1/movies/review", data) } updateReview(data){ return axios.put("{{EDUCATIVE_LIVE_VM_URL}}:3000/api/v1/movies/review", data) } deleteReview(id, userId){ return axios.delete("{{EDUCATIVE_LIVE_VM_URL}}:3000/api/v1/movies/review", {data:{review_id: id, user_id: userId}} ) } getRatings(){ return axios.get("{{EDUCATIVE_LIVE_VM_URL}}:3000/api/v1/movies/ratings") } } export default new MovieDataService()
Creating state variables using React hooks
Add the code given below to the movies-list.js
file:
import React, {useState, useEffect } from 'react'import MovieDataService from "../services/movies"import { Link } from "react-router-dom"const MoviesList = props => {const [movies, setMovies] = useState([])const [searchTitle, setSearchTitle] = useState("")const [searchRating, setSearchRating] = useState("")const [ratings, setRatings] = useState(["All Ratings"])}
Lines 1–3: We import useState
to create a series of state variables. Furthermore, we import the useEffect
(which we’ll describe later), MovieDataService
, and Link
modules.
Lines 5–11: MoviesList
is a functional component that receives and uses props
. We use the React useState
hook to create the movies
, searchTitle
, searchRating
, and ratings
state variables. The searchTitle
and searchRating
state variables keep track of what users have entered into the search form fields on the MoviesList
page.
Line 7: We set movies
to an empty array (usestate([])
) by default.
Lines 8–9: We set searchTitle
and searchRating
to an empty string by default.
Line 10: We set ratings
to an array with the value All Ratings
. This is because when a user first comes to the MoviesList
search form, the default value for search by ratings is All
...