Skip to content

Instantly share code, notes, and snippets.

@Astrochimp
Last active November 11, 2018 03:08
Show Gist options
  • Save Astrochimp/b5b4a5c5e71ea4b9e25dc7b437fd7b71 to your computer and use it in GitHub Desktop.
Save Astrochimp/b5b4a5c5e71ea4b9e25dc7b437fd7b71 to your computer and use it in GitHub Desktop.
import React, { Component } from 'react'
import axios from 'axios'
class Swapi extends Component {
constructor (props) {
super(props)
this.state = {
character: {},
movielist: [],
characterName: ''
}
this.getMovieList = this.getMovieList.bind(this)
}
componentDidMount () {
const SWAPI_API = 'https://swapi.co/api/people/1'
axios.get(SWAPI_API)
.then((character) => {
const charInfo = character.data
this.setState({
character: charInfo,
characterName: charInfo.name,
movielist: this.getMovieList(charInfo.films)
})
})
}
getMovieList (movies) {
let movieArr = []
movieArr = movies.map((movieurl) => {
return axios.get(movieurl)
.then((moviedata) => {
return ({
title: moviedata.data.title,
crawl: moviedata.data.opening_crawl
})
})
})
return Promise.all(movieArr)
.then((moviedata) => {
this.setState({
movielist: moviedata
})
})
.catch((err) => {
console.log('error', err)
})
}
render () {
let characterMovies = []
if (this.state.movielist.length > 0) {
characterMovies = this.state.movielist.map((film, ind) => <div key={ind}><h3>{film.title}</h3> <p>{film.crawl}</p></div>)
}
return (
<div>
<h1>Swapi</h1>
<h2>{this.state.characterName}</h2>
<div>
{characterMovies}
</div>
</div>
)
}
}
export default Swapi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment