Reputation: 131
I have a program that polls the weather every 30 seconds and I was getting CORS errors. I investigated it and saw that the city and country were being read as undefined.
I get my user data from my users' table then send them with an Axios request to the weather API:
return axios({
url: `https://europe-west1-hummid.cloudfunctions.net/api/weather`,
method: 'POST',
data: {
city: data?.city,
country: data?.country
},
headers: {
Authorization: `${authToken}`
},
I have but they're being sent as undefined. I currently have it set up using a useEffect to get the data from the users table
useEffect(() => {
const userRef = db.collection('users').doc(currentUserEmail);
userRef.get().then((doc) => {setData(toUser(doc));})
}, [currentUserEmail])
Then I pass it to a function that maps it to an interface:
export interface User {
userId: string;
fname: string;
lname: string;
country: string;
city: string;
email: string;
phone: number;
}
export function toUser(doc: firebase.firestore.DocumentSnapshot): User {
return {userId: doc.id, ...doc.data()} as User;
}
Is there a way to use my method of retrieving data or a better way to make sure I am not getting undefined values? Also, is the reason I am getting undefined because I am using optional chaining on the values?
Upvotes: 2
Views: 429
Reputation: 14844
I guess you problem here is that you make your axios request before having data in your data
state. Before making your request, you need to be sure that the state contains the data fetched from userRef.get().then((doc) => {setData(toUser(doc));})
.
A simple way to achieve that is to put your axios request in a useEffect
that listen changes on the data
state and do the fetch when data
is no more undefined
or null
:
React.useEffect(() => {
if (data) {
// Here fetch your API with data
// It won't contain any undefined
const { city, country } = data
axios({
url: `https://europe-west1-hummid.cloudfunctions.net/api/weather`,
method: 'POST',
data: {
city,
country
}
})
}
}, [data]);
Checkout the demo:
Upvotes: 3