· 5 years ago · Nov 17, 2020, 02:56 PM
1// Codedamn - React - Video 25 - implementing search API to Movies Store Project - this video sucks - had to study Promises on my own (big whoop - i am a big boy), and figure out how to put together the contents of the files as the video was dumbly edited/cut/corrupted. Wasted good time here but I guess learned a few things.
2
3// create Movies and Movie component
4// directory structure like so:
5src/components/Movies/index.tsx
6src/components/Movies/Movie/index.tsx
7
8// ----------------------------------------------------------------------
9
10// import in app.tsx file like you see below
11
12// App.tsx content:
13
14// ----------------------------------------------------------------------
15
16import React from 'react'
17import './App.css'
18import Header from './components/Header'
19import Movies from './components/Movies'
20
21function App() {
22 return (
23 <div className="App">
24 <Header/>
25 <Movies/>
26 </div>
27 );
28}
29
30export default App;
31
32// ----------------------------------------------------------------------
33
34// Movie index.tsx
35
36// ----------------------------------------------------------------------
37
38import React from 'react'
39
40type Props = {
41 title: string
42 year: string
43 image: string
44}
45
46const Movie: React.FC<Props> = props => {
47
48 console.log("movie props", props)
49
50 return (
51 <div className="movie">
52 <h2>{props.title}</h2>
53 <img src={props.image}/>
54 <h3>{props.year}</h3>
55 </div>
56 )
57}
58
59export default Movie
60
61// ----------------------------------------------------------------------
62
63// Movies index.tsx
64
65// ----------------------------------------------------------------------
66
67import React, { useEffect, useState } from 'react'
68import Movie from './Movie'
69
70const API_KEY = "eb7f19c3" // codecamps - my key 383e0fe3
71
72const series = [ 'the triangle', 'avengers', 'inception', 'interstellar' ]
73
74const Movies: React.FC = props => {
75
76 const [movies,setMovies] = useState([])
77
78 useEffect(() => {
79 const promises = series.map(series=>{return fetch(`http://www.omdbapi.com/?t=${encodeURIComponent(series)}&apikey=${API_KEY}&page=1`).then(
80 r=>{
81 let answer=r.json()
82 console.log("here:",answer);
83 return answer;
84 }
85 )
86 })
87
88 Promise.all(promises).then((movies: any) => {
89 setMovies(movies)
90
91 } )
92 }, [])
93
94 console.log("MOVIES:", movies)
95
96 return <div>
97 { movies.flat(2).map((movie:any) =>
98 <Movie
99 key={movie.imdbID}
100 title={movie.Title}
101 year={movie.Year}
102 image={movie.Poster}/> )}
103 </div>
104
105}
106
107export default Movies