質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.39%
API

APIはApplication Programming Interfaceの略です。APIはプログラムにリクエストされるサービスがどのように動作するかを、デベロッパーが定めたものです。

React.js

Reactは、アプリケーションのインターフェースを構築するためのオープンソースJavaScriptライブラリです。

Q&A

解決済

1回答

1571閲覧

[react] Weather API からデータを取得・検索し画面に表示させたい。

suzukitoshinari

総合スコア6

API

APIはApplication Programming Interfaceの略です。APIはプログラムにリクエストされるサービスがどのように動作するかを、デベロッパーが定めたものです。

React.js

Reactは、アプリケーションのインターフェースを構築するためのオープンソースJavaScriptライブラリです。

0グッド

1クリップ

投稿2021/01/30 07:28

編集2021/01/30 13:17

reactを使い、Weather Apiからデータを取得・検索し画面に表示させたいのですが、下記のエラーが出ており、表示できない状態です。

Error: Objects are not valid as a React child (found: object with keys {coord, weather, base, main, visibility, wind, clouds, dt, sys, timezone, id, name, cod}). If you meant to render a collection of children, use an array instead.

該当エラー箇所

src/Weather.js:59

56 | useEffect(() => {
57 | // const key = 'be690936e66de4f05bda2ccf9f534c2c';
58 | axios(http://api.openweathermap.org/data/2.5/weather?q=country&lang=ja&appid=be690936e66de4f05bda2ccf9f534c2c).then((res) => {

59 | setValue(res.data);

| ^ 60 | setWeather(res.data.weather[0].description);

61 | setTemperature(res.data.main);
62 | setImg(http://openweathermap.org/img/wn/res.data.weather[0].icon.png);

package.json

{

"name": "weather-app",
"version": "0.1.0",
"private": true,
"dependencies": {
"@material-ui/core": "^4.11.3",
"@material-ui/icons": "^4.11.2",
"@testing-library/jest-dom": "^5.11.4",
"@testing-library/react": "^11.1.0",
"@testing-library/user-event": "^12.1.10",
"axios": "^0.21.1",
"react": "^17.0.1",
"react-dom": "^17.0.1",
"react-scripts": "4.0.1",
"web-vitals": "^0.2.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}

追加箇所

xhr.js:177 GET http://api.openweathermap.org/data/2.5/weather?q=city&appid=%22be690936e66de4f05bda2ccf9f534c2c%22 401 (Unauthorized)

createError.js:16 Uncaught (in promise) Error: Request failed with status code 401

at createError (createError.js:16) at settle (settle.js:17) at XMLHttpRequest.handleLoad (xhr.js:62)

コード

import { Button, Paper, TextField } from "@material-ui/core"; import React, { useState, useEffect } from "react"; import SendIcon from "@material-ui/icons/Send"; import axios from "axios"; const Weather = () => { const [value, setValue] = useState(""); const [temp, settemp] = useState(""); const [typecity, settypecity] = useState(""); const [city, setcity] = useState("Delhi"); const [img, setimg] = useState(""); const [disc, setdisc] = useState(""); const citySelect = (e) => { e.preventDefault(); setcity(typecity); }; useEffect(() => { axios.get( `http://api.openweathermap.org/data/2.5/weather?q=city&appid="自身のAPI"` ).then((res) => { setValue(res.data); settemp(res.data.main); setimg( `http://openweathermap.org/img/wn/res.data.weather[0].icon.png` ); setdisc(res.data.weather[0].description); }); }, [city]); return ( <div> <Paper className="paper"> <form onSubmit={citySelect} className="elementcenter"> <TextField placeholder="type city here" value={typecity} onChange={(e) => settypecity(e.target.value)} /> <Button type="submit"> <SendIcon /> </Button> </form> <h6 className="fontcss">{value.name}</h6> <img src={img} alt="weather icon" className="imgcss" /> <h6 className="fontcss">{disc}</h6> <div className="elementcenter"> <p> Min <br /> {`${Math.floor(temp.temp_min - 273.15)}° C`} </p> <h6 className="fontcss">{`${Math.floor(temp.temp - 273.15)}° C`}</h6> <p> Min <br /> {`${Math.floor(temp.temp_max - 273.15)}° C`} </p> </div> </Paper> </div> ); }; export default Weather;

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

hoshi-takanori

2021/01/30 08:05

エラーが出てるのはそこではなく、JSX を render してるところだと思いますけど…。
suzukitoshinari

2021/01/30 08:43

ありがとうございます。次は質問文に追加したエラーが出ており、apiを取得できない感じです。 コードも追加しました。
guest

回答1

0

ベストアンサー

とりあえずこれで動くのでは。文字列中に値を埋め込むには、${変数名 (または式)} を使う必要があります。
参考: テンプレートリテラル (テンプレート文字列) - JavaScript | MDN

diff

1 useEffect(() => { 2+ const appid = "自身のAPI"; 3 axios.get( 4- `http://api.openweathermap.org/data/2.5/weather?q=city&appid="自身のAPI"` 5+ `http://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${appid}` 6 ).then((res) => { 7 setValue(res.data); 8 settemp(res.data.main); 9 setimg( 10- `http://openweathermap.org/img/wn/res.data.weather[0].icon.png` 11+ `http://openweathermap.org/img/wn/${res.data.weather[0].icon}.png` 12 ); 13 setdisc(res.data.weather[0].description); 14 }); 15 }, [city]);

(細かいことを言うと、エラーチェックした方がいいのでは、とか、valuetemp の値は文字列ではなくオブジェクトなので、初期値は "" じゃなくて {} の方がいいのでは、とか…。)

投稿2021/01/30 17:59

hoshi-takanori

総合スコア7899

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

suzukitoshinari

2021/01/31 04:31

ありがとうございます。また助けてもらいました
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.39%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問