Last active
September 27, 2018 16:55
-
-
Save aalokt89/e8bab794e3d2b73d7fe979cfc8ecd509 to your computer and use it in GitHub Desktop.
get random user from randomuser.me api
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as React from "react"; | |
import { PropertyControls, ControlType } from "framer"; | |
import { UserCell } from "./canvas"; | |
// Define type of property | |
interface Props { | |
width: number; | |
height: number; | |
gender: string; | |
} | |
interface State { | |
avatar: string; | |
name: string; | |
location: string; | |
} | |
export class RandomUser extends React.Component<Partial<Props>, State> { | |
// Set default properties | |
static defaultProps = { | |
height: 80, | |
gender: "random" | |
}; | |
// Items shown in property panel | |
static propertyControls: PropertyControls = { | |
gender: { | |
type: ControlType.SegmentedEnum, | |
options: ["random", "male", "female"], | |
optionTitles: ["R", "M", "F"], | |
title: "Gender" | |
} | |
}; | |
state: State = { | |
avatar: "", | |
name: "", | |
location: "" | |
}; | |
loadData(url) { | |
fetch(url) | |
.then(response => { | |
if (response.ok) return response.json(); | |
throw new Error("Request failed."); | |
}) | |
.then(data => { | |
this.setState({ | |
name: `${data.results[0].name.first} ${data.results[0].name.last}`, | |
avatar: data.results[0].picture.large, | |
location: `${data.results[0].location.city}, ${ | |
data.results[0].location.state | |
}` | |
}); | |
}) | |
.catch(error => { | |
console.log(error); | |
}); | |
} | |
componentDidMount() { | |
let url = | |
"https://randomuser.me/api/?results=1&nat=us&inc=name,location,picture"; | |
this.loadData(url); | |
} | |
componentDidUpdate(prevProps) { | |
let url = ""; | |
if (this.props.gender !== prevProps.gender) { | |
url = `https://randomuser.me/api/?results=1&nat=us&gender=${ | |
this.props.gender | |
}&inc=name,location,picture`; | |
} | |
this.loadData(url); | |
} | |
render() { | |
return ( | |
<UserCell | |
width={this.props.width} | |
name={this.state.name} | |
avatar={this.state.avatar} | |
location={this.state.location} | |
/> | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment