score:1
Your code is correct but as the guys said, the weather
object will initially set to empty object {}
so you just need to check it first.
const App = () => {
const [weather, setWeather] = useState(null) // change it to null for easier check
// useEffect() ...
if (!weather) {
return <div>Loading indicator</div>
}
return (
<div className="App">
<Header api={weather} />
</div>
)
}
score:1
You are getting that error because you are trying to access a key that doesn't exist in the object. In the following weather is set to an empty object.
// remove this from your code
console.log('weather', weather);
// this will throw an error, since weather is an empty object.
console.log(weather.weather[0].icon);
import React, { useEffect, useState } from "react";
import axios from "axios";
import { Header } from "./Header";
export const CurrentCity = () => {
const [weather, setWeather] = useState({});
useEffect(() => {
async function getData() {
const url = `https://api.openweathermap.org/data/2.5/weather?q=Berlin&appid=${
process.env.REACT_APP_WEATHER_KEY
}`;
try {
const response = await axios.get(url);
setWeather(response.data);
} catch (err) {
console.log(err);
}
}
getData();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return (
<div>
<Header api={weather} />
</div>
);
};
Then in your header validate your data, don't assume that you'll always get the right data.
import React from "react";
export const Header = props => {
console.log(props);
return (
<div>
{/* here validate your data */}
<h1>{props && props.api && props.api.name}</h1>
</div>
);
};
You can also add a loader to show the user that you are fetching data from the server.
export const CurrentCity = () => {
const [weather, setWeather] = useState({});
const [isLoading, setIsLoading] = useState(true);
const [isError, setIsError] = useState(false);
useEffect(() => {
async function getData() {
const url = `https://api.openweathermap.org/data/2.5/weather?q=Berlin&appid=${
process.env.REACT_APP_WEATHER_KEY
}`;
try {
const response = await axios.get(url);
setWeather(response.data);
setIsLoading(false);
} catch (err) {
setIsError(true);
setIsLoading(false);
console.log(err);
}
}
getData();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return (
<>
{isLoading ? (
<h1>Loading ...</h1>
) : isError ? (
<p>Something went wrong</p>
) : (
<Header api={weather} />
)}
</>
);
};
Source: stackoverflow.com
Related Query
- Unable to access/manipulate data from weather API using axios with useEffect in React.js
- using useEffect in combination with Axios fetching API data returns null - how to deal with this?
- React Hook useEffect : fetch data using axios with async await .api calling continuous the same api
- Not able to resolve issue with api of OpenWeatherApi for fetching weather data of a city using City id using axios in Reactjs
- react get data from rest api with axios and and useEffect redering empty array plus array with data
- How do I access data returned from an axios get to display on a web page using react js?
- Unable to access returned data from a refetchQueries with Apollo and GraphQL
- I can't fetch data from the api using useEffect
- Delete data from API with Axios and ReactJS
- how to set an useEffect to fetch data from API at first render with eslint-react-hooks?
- Can't access array data from API call when using map() in React
- use axios with react to get data from api
- React redux frontend not fetching data from Django API with axios
- Render JSON data with keys from an API using map
- The data I want to get from API using Axios returns undefined
- Using data from API JSON object using Axios and React
- Unable to receive data in a Web API HttpPost method from React axios post
- Trying to fetch axios data with redux, and load it in a component using useEffect
- fetching data from the Dog API using axios and saving data into a new array
- Fetching Data from API using UseEffect
- Update data from array with multiple objects using Axios PUT request
- Display data from API using react component and useEffect
- For some reason, cant get the data from an api to render on the screen using axios in Reactjs
- 'Access-Control-Allow-Origin' error when getting data from the API with Axios (React)
- React and Express: Using Axios to GET data from 3rd party API
- Fetching data from Api in Reactjs using Axios
- how fetch data from database through api using axios in reactjs?
- Pulling data from an API using Axios on react.js. What am I doing wrong?
- I cannot collect data from API using Axios + React
- Unable to get data from api using Nextjs
More Query from same tag
- Positioning form input in React
- How to test Redux action creators
- How to redo API Calls in ReactJS everytime state gets changed?
- If suppose 2nd Render is same as 1st Render then 1st Render will unmounts or not?
- How can I do custom event for component in react?
- React FormEvent<HTMLFormElement> form input props types
- How to get the element ID into scroll view to mark category in navbar
- React's component hierarchy makes it awkward to re-arrange tags. Is there a remedy?
- Eslint react/jsx-one-expression-per-line: allow variables and JSX strings on the same line, but not elements
- API call in ReactJS and setting response to state
- How to loop through complex object using Map in React
- How to import CSS file on Isomorphic React - Webpack
- react basic multiple element rendering
- Should I use custom event delegation in React JS
- Please help, I can't get my reset button to work- React js
- Why is the keyboard (onKeyDown) event bubbling not accessible on the component, but is on the parent?
- eslint error Unary operator '++' used no-plusplus
- Formik validation not working for my custom react-places-autocomplete component
- Missing required parameter To in the post body in react js axios using spring boot Twilio Api
- How to place an image folder in a react app for production/development
- How to configure craco to use jsx?
- Can we add state name dynamically in react
- Is it possible to read xlsx in react if office is not installed on windows machine?
- how to set value in react-select
- Update array based on current time
- flask+react website using App Engine, url not found
- How do I write the content attribute in react?
- Cannot setState - tried with Axios, AJAX and fetch()
- styled-components onFocus and onBlur event does not work
- How can I fetch data from yelp api in React JS?