Skip to content

Instantly share code, notes, and snippets.

@omas-public
Last active February 25, 2019 07:33
Show Gist options
  • Save omas-public/7828bab7065e630f56bbc8ef9f16faf3 to your computer and use it in GitHub Desktop.
Save omas-public/7828bab7065e630f56bbc8ef9f16faf3 to your computer and use it in GitHub Desktop.
WebAPI React Sample
/*
現在地の高度を取ってくる
*/
import React, { Component } from 'react'
export default class App extends Component {
setElevationData = res => {
this.setState({
elevation : res.elevation
})
}
getElevationData = async (lat,lon) => {
const uri = 'http://cyberjapandata2.gsi.go.jp/general/dem/scripts/getelevation.php'
const option = { mode: 'cors' } // cors
const query = `?lat=${lat}&lon=${lon}&outtype=json`
return fetch(uri + query, option)
.then(res => res.json())
}
getCurrentPosition = async (options) => {
return new Promise((resolve, reject) =>
navigator.geolocation.getCurrentPosition(resolve, reject, options)
).then(res => ({
latitude: res.coords.latitude,
longitude : res.coords.longitude,
})
)
}
constructor(props) {
super(props)
this.state = {
elevation : null
}
}
async componentWillMount() {
const pos = await this.getCurrentPosition()
const res = await this.getElevationData(pos.latitude, pos.longitude)
this.setElevationData(res)
}
render() {
return (
<div>
<h1>現在地の標高</h1>
<SimpleView elevation = {this.state.elevation} />
</div>
)
}
}
const SimpleView = props => {
console.log(props)
const elevation = props.elevation || 0
const message = (Number(elevation, 10) < 10) ? '危険です' : '安全です'
return (
<div>
<div>{elevation}m {message}</div>
</div>
)
}
/*
require fetch-jsonp
星座ごとの本日の占いを取得
*/
import React, { Component } from 'react'
import fetchP from 'fetch-jsonp'
export default class App extends Component {
// 4: 必要なデータをセット
setData = res => {
const horoscope = res.reduce((acc, o) => {
acc[o.sign] = o
return acc
}, {})
this.setState({horoscope:horoscope})
}
// 3: fetch を使ってデータを取得
getData = async (value) => {
const url = 'http://api.jugemkey.jp/api/horoscope/free/jsonp/'
return await fetchP(url)
.then(res => res.json())
.then(json => Object.values(json.horoscope))
.then(array => array[0])
}
// 6: イベント発生時にデータを取得する
handleUpdate = value => {
console.log(value)
this.setState({sign:this.state.horoscope[value]})
}
// 1: データの初期化 取得するプロパティがわかっているなら全部初期化するとNull処理をしなくてよい
constructor(props) {
super(props)
this.state = {
horoscope:{},
sign:{
color: null,
content: null,
day: null,
item: null,
job: null,
love: null,
money: null,
rank: null,
sign: null,
total: null
}
}
}
// 2: 最初からデータを取得するならここで行う,async,awaitで同期処理に変換している
async componentWillMount() {
const res = await this.getData()
this.setData(res)
}
// 5, 7 データの表示,イベント処理
render() {
console.log(this.state)
return (
<div>
<h1>今日の星座占い</h1>
<SimpleInput handleUpdate={this.handleUpdate} />
<SimpleView horoscope = {this.state.sign} />
</div>
)
}
}
const SimpleView = props => {
const {content, rank, color, item, sign, ...rest} = props.horoscope
console.log(content, rank, color, item)
const data = [
{ subject: '総合', rank: rest.total},
{ subject: '仕事運', rank: rest.job},
{ subject: '金運', rank: rest.money},
{ subject: '恋愛運', rank: rest.love}
]
return (
<div>
<p>{content}</p>
<p>本日の{sign} {rank || '??'}位</p>
<ul>
<li>ラッキーカラー :{color}</li>
<li>ラッキーアイテム:{item}</li>
</ul>
</div>
)
}
const SelectItems = text =>
<option value = {text} key = {text}>{text}</option>
class SimpleInput extends Component {
textChange = event => {
const value = event.target.value
this.setState({sign: value})
}
buttonClick = () => {
this.props.handleUpdate(this.state.sign)
}
constructor (props) {
super(props)
this.state = {sign:null}
}
render () {
const signs = ['','牡羊座','牡牛座','双子座','蟹座', '獅子座','乙女座',
'天秤座','蠍座', '射手座','山羊座','水瓶座','魚座']
return (
<form>
<select onChange = {this.textChange}>{signs.map(SelectItems)}</select>
<input type="button" value = "submit" onClick={this.buttonClick} />
</form>
)
}
}
/*
reqire pokemon
pokemonの 名前から英語名と画像を取ってくる
*/
import React, { Component } from 'react'
import pokemon from 'pokemon';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'
import AutoComplete from 'material-ui/AutoComplete'
import Button from 'material-ui/RaisedButton';
export default class App extends Component {
// 4: 必要なデータをセット
setData = res => {
console.log(res.name, res.sprites)
this.setState({
name:res.name,
images:res.sprites
})
}
// 3: fetch を使ってデータを取得
getData = async (pokeid) => {
const uri = `https://pokeapi.co/api/v2/pokemon-form/`;
const option = { mode: 'cors' } // cors
const query = `${pokeid}`
return fetch(uri + query, option)
.then(res => res.json())
}
// 6: イベント発生時にデータを取得する
handleUpdate = async pokeid => {
const res = await this.getData(pokeid)
this.setData(res)
}
// 1: データの初期化 取得するプロパティがわかっているなら全部初期化するとNull処理をしなくてよい
constructor(props) {
super(props)
this.state = {
name:null,
images:{}
}
}
// 5, 7 データの表示,イベント処理
render() {
return (
<div>
<MuiInput handleUpdate={this.handleUpdate} />
<SimpleView data = {this.state} />
</div>
)
}
}
class MuiInput extends Component {
handleUpdate = event => {
const pokeid = pokemon.getId(
this.refs.pokeid.state.searchText, 'ja');
this.props.handleUpdate(pokeid);
}
render () {
return (
<MuiThemeProvider>
<div>
<AutoComplete
hintText="Type Pokemon name"
fullWidth = {true}
dataSource={pokemon.all('ja')}
ref = 'pokeid' />
<Button onClick = {this.handleUpdate}>
Send
</Button>
</div>
</MuiThemeProvider>
)
}
}
const SimpleView = props => {
const {name, images} = props.data
return (
<div>{name}
<img src = {images['front_default']} alt = {name} />
<img src = {images['back_default']} alt = {name} />
</div>
)
}
/*
WebAPIのテンプレート
*/
import React, { Component } from 'react'
export default class App extends Component {
// 4: 必要なデータをセット
setData = res => {
console.log(res)
this.setState({
xxx:res.xxx,
yyy:res.yyy
})
}
// 3: fetch を使ってデータを取得
getData = async (value) => {
const uri = ''
const option = { mode: 'cors' } // cors
const query = `?q=${value}`
return fetch(uri + query, option)
.then(res => res.json())
}
// 6: イベント発生時にデータを取得する
handleUpdate = value => {
const res = await this.getData(value)
this.setData(res)
}
// 1: データの初期化 取得するプロパティがわかっているなら全部初期化するとNull処理をしなくてよい
constructor(props) {
super(props)
this.state = {
xxx:null,
yyy:null
}
}
// 2: 最初からデータを取得するならここで行う,async,awaitで同期処理に変換している
async componentWillMount() {
const res = await this.getData()
this.setData(res)
}
// 5, 7 データの表示,イベント処理
render() {
return (
<div>
<SimpleInput handleUpdate={this.handleUpdate} />
<SimpleView data = {this.state} />
</div>
)
}
}
const SimpleView = props => {
const {} = props.data
return (
<div>
</div>
)
}
class SimpleInput extends Component {
textChange = event => {
const value = event.target.value
this.setState({???: value})
}
buttonClick = () => {
const value = this.state.???
this.props.handleUpdate()
}
constructor (props) {
super(props)
this.state = {???:null}
}
render () {
return (
<form>
<label>Input:<input type="text" onChange={this.textChange}/>
</label><input type="button" value = "submit" onClick={this.buttonClick} />
</form>
)
}
}
/*
現在地の天気を取ってくる
*/
import React, { Component } from 'react'
export default class App extends Component {
setWeatherData = res => {
console.log(res)
this.setState({
place:res.name,
weather:res.weather[0].description,
icon:res.weather[0].icon,
temp:res.main.temp,
})
}
getWeatherData = async (lat,lon) => {
const uri = 'https://api.openweathermap.org/data/2.5/weather'
const token = 'XXXXXXXXXXXXXXXXXXX'
const option = { mode: 'cors' } // cors
const query = `?lat=${lat}&lon=${lon}&appid=${token}&lang=ja&units=metric`
return fetch(uri + query, option)
.then(res => res.json())
}
getCurrentPosition = async (options) => {
return new Promise((resolve, reject) =>
navigator.geolocation.getCurrentPosition(resolve, reject, options)
).then(res => ({
latitude: res.coords.latitude,
longitude : res.coords.longitude})
)
}
constructor(props) {
super(props)
this.state = {
place:null,
weather:null,
icon:null,
temp:null
}
}
async componentWillMount() {
const pos = await this.getCurrentPosition()
const res = await this.getWeatherData(pos.latitude, pos.longitude)
this.setWeatherData(res)
}
render() {
return (
<div>
<SimpleView data = {this.state} />
</div>
)
}
}
const SimpleView = props => {
const {place, weather, temp, icon} = props.data
return (
<div>
<h1>気象情報 {place}</h1>
<ul>
<li>天気:{weather}</li>
<li>気温:{temp}</li>
</ul>
</div>
)
}
/*
郵便番号から住所を取得
*/
import React, { Component } from 'react'
export default class App extends Component {
webAPI = async zipcode => {
const uri = 'https://api.zipaddress.net/'
const option = { mode: 'cors' } // cors
const query = `?zipcode=${zipcode}`
return fetch(uri + query, option)
.then(res => res.json())
.then(json => json.data)
.then(data => ({pref:data.pref,city:data.city,town:data.town}))
.catch(console.log)
}
setZipData = async zipcode => {
const res = await this.webAPI(zipcode)
this.setState({ data: res })
}
handleUpdate = zipcode => {
this.setZipData(zipcode)
}
constructor(props) {
super(props)
this.state = {
data: {
pref: null,
city: null,
town: null,
}
}
}
render() {
return (
<div>
<h1>郵便番号検索フォーム</h1>
<SimpleInput handleUpdate={this.handleUpdate} />
<SimpleView data={this.state.data} />
</div>
)
}
}
const SimpleView = props => {
const {pref, city, town} = props.data
return (
<div>
<label>{pref}</label>
<label>{city}</label>
<label>{town}</label>
</div>
)
}
class SimpleInput extends Component {
textChange = event => {
this.setState({zipcode:event.target.value})
}
buttonClick = () => {
this.props.handleUpdate(this.state.zipcode)
}
constructor (props) {
super(props)
this.state = {zipcode:null}
}
render () {
return (
<form>
<label>Zipcode:<input type="number" onChange={this.textChange}/>
</label><input type="button" value = "submit" onClick={this.buttonClick} />
</form>
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment