暫時揮別 react router 的部分,
這次來實作一個小型的互動程式,用 react hook 及 axios 向 api 取得特定城市的氣溫資料
如果使用 npm 的話
npm install axios
如果使用 yarn 的話
yarn add axios
codeSandBox的話,只要從左邊加進環境就可以了
這裡只簡單介紹最基本的用法囉,細節參見官方文件會比較清楚
get
axios.get('url')
.then(function(response){
// handle success
})
.catch(function(error){
// handle error
})
.then(function(){
// always executed
})
這裡使用的是 open-meteo.com 的免費 api
不可以商用喔,這部分務必多加注意~
分成
DashBoard.js
要使用 axios 前,要記得 import 進來
import { useState, useEffect } from "react";
import axios from "axios";
建立基本城市的經緯度資料等等
const CITIES = [
{ name: "Taipei", latitude: 25.105, longitude: 121.597 },
{ name: "Taichung", latitude: 24.147, longitude: 120.673 },
{ name: "Kaohsiung", latitude: 22.633, longitude: 120.266 }
];
這裡先用多個 state 跟最簡單的 useState 來設定 state ,有空再寫的精簡些XD(確診中腦袋有點昏沈
向 api 取 data 的 axios function 先暫時放在 useEffect 內,之後會再修改
DashBoard.js
import { useState, useEffect } from "react";
import axios from "axios";
import Dropdowns from "./Dropdowns";
const CITIES = [
{ name: "Taipei", latitude: 25.105, longitude: 121.597 },
{ name: "Taichung", latitude: 24.147, longitude: 120.673 },
{ name: "Kaohsiung", latitude: 22.633, longitude: 120.266 }
];
export default function DashBoard() {
const [temperature, setTemperature] = useState(null);
const [city, setCity] = useState(null);
const [geo, setGeo] = useState({ lat: null, lon: null });
const handleChange = (evt) => {
setCity(evt.target.value);
let geoInfo = null;
evt.target.value === "Taipei"
? (geoInfo = { lat: CITIES[0].latitude, lon: CITIES[0].longitude })
: evt.target.value === "Taichung"
? (geoInfo = { lat: CITIES[1].latitude, lon: CITIES[1].longitude })
: (geoInfo = { lat: CITIES[2].latitude, lon: CITIES[2].longitude });
setGeo(geoInfo);
};
useEffect(() => {
const url = `https://api.open-meteo.com/v1/forecast?latitude=${geo.lat}&longitude=${geo.lon}&hourly=temperature_2m`;
const fetchData = async () => {
const result = await axios(url);
console.log(result);
console.log(result.request.response);
setTemperature(result.request.response);
};
fetchData();
}, [geo.lat, geo.lon]);
return (
<div>
<Dropdowns data={CITIES} onChange={handleChange} />
{city && true ? <h2>{city}</h2> : <p>not select city yet</p>}
<a href="https://open-meteo.com/">Weather data by Open-Meteo.com</a>
</div>
);
}
Dropdowns 負責接收父層組建傳下來的 props,用 props 產生對應的 options
以及 onChange 時改變選取的 value
Dropdowns.js
export default function Dropdowns(props) {
const { data, onChange } = props;
const options = data.map((each) => (
<option value={each.name} label={each.name}>
{each.name}
</option>
));
return (
<div>
<select onChange={onChange}>{options}</select>
</div>
);
}
今天的codeSandBox一樣在這裏
明天接續寫
https://www.npmjs.com/package/axios
https://axios-http.com/docs/example
https://open-meteo.com/en/docs#api-documentation
fetch data
https://www.robinwieruch.de/react-hooks-fetch-data/