Reputation: 170
I am trying to make a front-end website using react, and I am using the APIs that NASA has. My main question pertains to the 4 Mars Rovers: Curiosity, Opportunity, Spirit, and Mission Manifest. Each of these Rovers have an API related to them that give out pictures that they have taken, and I handled the first Rover like this:
//App.js
onTermSubmit = async (term) =>{
const response = await MarsPics_Curiosity.get('',{
params:{
earth_date: term,
api_key: 'KEY'
})
this.setState({Marspictures_Curiosity: response.data.photos, MarsDate_Curiosity: term})
}
And I was thinking of make 3 more of these to call the rest of the rover APIs. But then, I kind of realized that it seems kind of redundant and repetitive. So, I was wondering if there is a better way to handle this without making 3 more separate functions?
Upvotes: 1
Views: 102
Reputation: 9095
So in your case since you don't want to write again and again the function what you can do is make the function static and whatever changes in the function like url, params, pass it as params to the function
onFetchData = async (url,params) =>{
const response = await MarsPics_Curiosity.get(url,{
...params
})
this.setState({Marspictures_Curiosity: response.data.photos, MarsDate_Curiosity: term})
}
And call the function as and pass the required params,
const resp1 = await onFetchData('/api1', {date: '2020-01-06'})
const resp2 = await onFetchData('/api2', {name: 'Mars'})
One advantge on this basically you can have error for each one and show the error message if one fails
As @Andus mentioned in the comment you can use Promise.all
, but if one fails everything gets failed. So basically it returns all the success response in an array or if one got failed it will send the error. You can read more on here
I hope this will get you better view of the problem
Upvotes: 1
Reputation: 3032
You can pass the name of rover into your function and calculate fields and objects names according this parameter
async (term, roverName) =>{
const response = await window["MarsPics_" + roverName].get('',{
params:{
earth_date: term,
api_key: 'KEY'
})
this.setState({
["Marspictures_" + roverName]: response.data.photos,
["MarsDate_" + roverName]: term
})
}
```
Upvotes: 1