ReactJS data from API - reactjs

Hello guys when i'm running this code in ReactJS
const callApi = async () => {
const response = await axios.get('http://api.openweathermap.org/data/2.5/weather?q=London&units=metric&appid=mykey');
setWeather(response)
}
i can get to console.log(weather.data) but when i try to get console.log(weather.data.main)
i get this error TypeError: Cannot read property 'main' of undefined i tried to parse that data to JSON but that didnt work either.
Here you can see that this object has this property:
{
"coord": {
"lon": -0.13,
"lat": 51.51
},
"weather": [
{
"id": 804,
"main": "Clouds",
"description": "overcast clouds",
"icon": "04n"
}
],
"base": "stations",
"main": {
"temp": 12.43,
"feels_like": 7.81,
"temp_min": 11.67,
"temp_max": 13,
"pressure": 1010,
"humidity": 62
},
.....other items
}
Thank you for all answers.

Sometimes during the first render data isn't defined yet so use:
console.log(weather.data?.main)
and works like a if(data)

Related

TypeError: Cannot read property 'temp' of undefined

I am trying to access data from OpenWeather API and it has nested objects and I keep getting the error trying to access data in these nested objects. I can access values from the parent object but no from nested ones.
this is me passing data to the component.
const Card = ({ cardRef }) => {
const [data, setData] = useState({});
useEffect(() => {
setData({ ...cardRef });
console.log(data.main.temp);
}, [cardRef]);
I can access data.main but not data.main.temp
below in the data being passed
{
"coord": {
"lon": -0.2,
"lat": 5.56
},
"weather": [
{
"id": 500,
"main": "Rain",
"description": "light rain",
"icon": "10d"
}
],
"base": "stations",
"main": {
"temp": 304.15,
"feels_like": 304.86,
"temp_min": 304.15,
"temp_max": 304.15,
"pressure": 1011,
"humidity": 66
},
"visibility": 10000,
"wind": {
"speed": 7.2,
"deg": 190
},
"rain": {
"1h": 0.29
},
"clouds": {
"all": 20
},
"dt": 1607092023,
"sys": {
"type": 1,
"id": 1126,
"country": "GH",
"sunrise": 1607061413,
"sunset": 1607103947
},
"timezone": 0,
"id": 2306104,
"name": "Accra",
"cod": 200
}
Since setData is the asynchronous method, you can't get the updated value of data immediatley after setData.
const Card = ({ cardRef }) => {
const [data, setData] = useState({});
useEffect(() => {
setData({ ...cardRef });
console.log(data.main.temp); // data is still the old value which is initial empty {} value, so `data.main` is undefined and `data.main.temp` will be error.
}, [cardRef]);
You should get it inside useEffect with adding a data dependency.
useEffect(() => {
if (data.main) { // Make sure that you need to check if `data.main` is not undefined before referring `data.main.temp`.
console.log(data.main.temp);
}
}, [data]);

I am trying to call Weather API using React and Axios I am trying to console.log the result but its saying the undefined... :(

When I am trying the console log the state its saying Undefined.. I also placed the JSON file.
I have posted the endpoint json file here. I believe there is an issue while hooking up json.
When I am trying the console log the state its saying Undefined.. I also placed the JSON file.
I have posted the endpoint json file here. I believe there is an issue while hooking up json.
class App extends Component {
state = {
content: [{ coord: "" }, { base: "" }]
};
componentDidMount() {
axios
.get(
"https://api.openweathermap.org/data/2.5/weather?q=berlin&appid=240ef553958220e0d857212bc790cd14"
)
.then(res => {
this.setState({
content: [
{
coord: res.data.coord
},
{ base: res.data.base }
]
});
});
}
render() {
console.log(this.state.content.coord);
return (
<div className="App center">
<h2 className="blue-text">Weather App</h2>
<div></div>
<Weather />
</div>
);
}
}
export default App;
JSON endpoint goes here....
{
"coord": {
"lon": 13.41,
"lat": 52.52
},
"weather": [
{
"id": 803,
"main": "Clouds",
"description": "broken clouds",
"icon": "04n"
}
],
"base": "stations",
"main": {
"temp": 276.88,
"feels_like": 268.47,
"temp_min": 275.37,
"temp_max": 278.15,
"pressure": 994,
"humidity": 80
},
"visibility": 10000,
"wind": {
"speed": 9.3,
"deg": 240,
"gust": 14.4
},
"clouds": {
"all": 75
},
"dt": 1580260557,
"sys": {
"type": 1,
"id": 1275,
"country": "DE",
"sunrise": 1580280826,
"sunset": 1580312685
},
"timezone": 3600,
"id": 2950159,
"name": "Berlin",
"cod": 200
}
As content is an array type you can access coord or base directly. Instead change it to an object or access it based on array index like this.
this.state.content[0].coord / this.state.content[1].base
If you change content to object type you can access coord or base directly as i did it here
sample code:
state = {
content: { coord: "", base: "" }
};
after request fetch you can update state something like this.
this.setState({
content: { coord: res.data.coord, base: res.data.base }
});
You can make your state look like below which make reading and accessing the data easier.
state = {
content: {
coord: "",
base: "",
},
}
and your setState like below:
this.setState({
content: {
coord: res.data.coord,
base: res.data.base
}
})

Can't access the nested objects but can render the non-nested ones from API (using React hooks)

I'm a bit stumped on this problem I encountered trying to render the data from an API. Weird thing is I successfully fetched the data and I can render the values of properties in the array but the moment it becomes a nested property within an array it returns undefined. Do you by any chance know why?
location[0] + '&lon=' +
location[1] + '&APPID=8e6150cf719d58fc8062d507eaba92c0'
const [data, loading] = useFetch(url);
console.log(data.main.temp) // returns undefined
console.log(data.name) // logs name
The useFetch() is the following:
useEffect(() => {
async function fetchUrl() {
const response = await fetch(url);
const json = await response.json();
setData(json);
setLoading(false);
}
fetchUrl();
}, [url]);
return [data, loading];
}
export { useFetch };
The error message is:
TypeError: Cannot read property 'temp' of undefined
Data fetched looks like this:
{
"coord": {
"lon": 2.18,
"lat": 41.42
},
"weather": [
{
"id": 800,
"main": "Clear",
"description": "clear sky",
"icon": "01n"
}
],
"base": "stations",
"main": {
"temp": 293.81,
"pressure": 1013,
"humidity": 77,
"temp_min": 292.04,
"temp_max": 294.82
},
"visibility": 10000,
"wind": {
"speed": 2.6,
"deg": 120
},
"clouds": {
"all": 0
},
"dt": 1561061585,
"sys": {
"type": 1,
"id": 6414,
"message": 0.0074,
"country": "ES",
"sunrise": 1561004254,
"sunset": 1561058875
},
"timezone": 7200,
"id": 3124932,
"name": "el Clot",
"cod": 200
}

Accessing group of data after fetching data from API with reactjs

I am learning react and stumbled on something that seems like an absolute beginner problem. Anyway I am fetching data from an API and would like to know how to get a certain element from the JSON. I have tried different variations with [0] but with no success.
here is .json:
{
"data": [
{
"id": 68,
"name": "Umrah bersama Da'i Hadhari",
"duration": "12D10N",
"slug": "umrah-bersama-dai-hadhari-november-disember",
"type": "umrah",
"isPublished": true,
"isHighlighted": true,
"promoStatus": null,
"tourCode": null,
"displayName": "Umrah bersama Da'i Hadhari",
},
{
"id": 70,
"name": "Umrah bersama Da'i Fuad",
"duration": "12D10N",
"slug": "umrah-bersama-dai-fuad-2018",
"type": "umrah",
"isPublished": true,
"isHighlighted": true,
"promoStatus": null,
"tourCode": "UGOCT18-ECON",
"displayName": "Umrah bersama Da'i Fuad",
},
{
"id": 45,
"name": "Umrah Super Ekonomi - Disember",
"duration": "12D10N",
"slug": "ugdec18-umrah-disember-cuti-sekolah",
"type": "umrah",
"isPublished": true,
"isHighlighted": true,
"promoStatus": null,
"tourCode": "UGOCT18 - P/FB",
"displayName": "Umrah Super Ekonomi - Disember",
},
{
"id": 47,
"name": "Umrah Super Ekonomi - November",
"duration": "12D10N",
"slug": "ugnov18-p-fb-umrah-november-cuti-sekolah-musim-sejuk",
"type": "umrah",
"isPublished": true,
"isHighlighted": true,
"promoStatus": null,
"tourCode": "UGNOV18 - S.ECON",
"displayName": "Umrah Super Ekonomi - November",
},
]
}
here is my code:
class PackageDetails extends React.Component {
constructor (props) {
super (props);
this.state = {
data: [],
}
}
componentDidMount () {
fetch ('http://localhost/sampleData.json')
.then ((Response) => Response.json())
.then ((findresponse) => {
console.log(findresponse.data[0])
this.setState({
data:findresponse.data[0],
})
})
}
render () {
return (
<div>
<Navigation/>
<Breedcrumbs/>
<section className="section-highlight">
<div className="container">
{
this.state.data.map((dynamicData,i) =>
<ContentHighlight
name={dynamicData.name}
packageType={dynamicData.packageType}
highlight={dynamicData.highlight}
/>
)
}
</div>
</section>
</div>
)
}
}
export default PackageDetails;
I just want to access the the first set of the data. it's working on console.log but not on this.setState.
please help me on this. thanks
this.state.data.map iterates through an array. Since this.state.data is an object, please use it directly like so:
<ContentHighlight
name={this.state.data.name}
packageType={this.state.data.packageType}
highlight={this.state.data.highlight}
/>

Openweathermap API Forecast accessing array

So I'm trying to mess around with the openweathermap API and I can't figure out how to access some of the data.
Here the snippet of code I have that access the API.
public void find_forecast () {
String url = "http://api.openweathermap.org/data/2.5/forecast?id=4466033&appid=e4c641dd837c7947a127972091185dad&units=imperial";
JsonObjectRequest jor = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray array = response.getJSONArray("list");
JSONObject object = array.getJSONObject(1);
String description = object.getString("dt");
day1.setText(description);
Here is a snippet of the API code:
{
"cod": "200",
"message": 0.0042,
"cnt": 40,
"list": [
{
"dt": 1524614400,
"main": {
"temp": 63.77,
"temp_min": 63.77,
"temp_max": 64.26,
"pressure": 1017.45,
"sea_level": 1021.4,
"grnd_level": 1017.45,
"humidity": 97,
"temp_kf": -0.27
},
"weather": [
{
"id": 500,
"main": "Rain",
"description": "light rain",
"icon": "10n"
}
],
So as you can see the code above will return the value of dt which is 1524614400. But I'm trying to access for example under "weather" the "description" which in this case is light rain. I guess I don't know how to access an array inside an array, although I couldn't even get the "temp" to return under "main", although I could get "main" to return everything underneath it.
Thanks for any help.
Max
Not sure about Android but in Javascript I would try this:
var dataObj = {
"cod": "200",
"message": 0.0042,
"cnt": 40,
"list": [
{
"dt": 1524614400,
"main": {
"temp": 63.77,
"temp_min": 63.77,
"temp_max": 64.26,
"pressure": 1017.45,
"sea_level": 1021.4,
"grnd_level": 1017.45,
"humidity": 97,
"temp_kf": -0.27
},
"weather": [
{
"id": 500,
"main": "Rain",
"description": "light rain",
"icon": "10n"
}
]
}
]
}
console.log(dataObj.list[0].weather[0].description);
I finally figured this out. Code is below!
String array = response.getJSONArray("list").getJSONObject(0).getJSONArray("weather").getJSONObject(0).getString("description");
day1.setText(array);
This will return light rain from the API code above.

Resources