Creating the Movie Component
Learn how to render data retrieved from the backend in React.
We'll cover the following...
In this lesson, we’ll create a Movie
component that will display the individual movie and its reviews:
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()
Initial files we will build on
In the components
folder in the movie.js
file, fill in the following code:
Press + to interact
import React, {useState, useEffect} from 'react'import MovieDataService from '../services/movies'import { Link } from 'react-router-dom'const Movie = props => {const [movie, setMovie] = useState({id: null,title: "",rated:"",reviews:[]})const getMovie = id =>{MovieDataService.get(id).then(response => {setMovie(response.data)console.log(response.data)}).catch(e =>{console.log(e)})}useEffect(()=>{getMovie(props.match.params.id)},[props.match.params.id])return (<div></div>);}export default Movie;
Lines 7–12: We have a movie
state variable to hold the specific movie we’re currently showing in the Movie
component. We set its initial values to null
, empty strings ""
, or an empty array []
.
Lines 14–23: The getMovie()
method calls the get()
method of MovieDataService
...