React axios triggers bunch get requests - javascript

I have a server and a route('/is-working') in which I render simply Yes or No, in React I do a get request with Axios every second with the use of intervals to see if its working.
Here is the code:
useEffect(() => {
const interval = setInterval(async () => {
await axios.get('http://192.168.1.57/is-working')
.then(res => {
if (res?.status === 200) {
// Do somthing
}
})
.catch(err => {
return Promise.reject(err);
})
}, 1000);
return () => clearInterval(interval);
}, []);
I want to count the number of times I get a 200 response back, when I stop hosting http://192.168.1.57/is-working and it returns an network error, until now everything is fine, but when I start hosting http://192.168.1.57/is-working again it does a bunch of get requests all together. It seems its requesting all of the ones that returned network error again.
thanks for the help in advance.

That must be because you didn't defined a timeout for axios client. So, it still trying to request your endpoint, once it comes back it does all request at once
Take a look here: https://github.com/axios/axios#axioscreateconfig

Related

How to slow down a single request / API endpoint for development?

EDIT: I am asking to slow down a SINGLE api call. Not the whole network. And I can't change the actual response time server side.
I am working in React. One component makes use of an API endpoint that sometimes takes very long. Every time that happens we allow the user to save, due to a bug.
I want to know how to slow down just that one API call, in order to create that particular situation.
So, I have for example
setLoading(true)
const templates = await getTemplates(dispatch)
setLoading(false)
in one component.
I would like to know what options I have to simulate that API response taking n seconds. No matter if doing that by code, tooling, etc..
setTimeout() on the server to delay sending the response, or on the client before resolving the promise.
EDIT: The code depends on your particular implementation/tools. Please share a snippet from your client-side function which calls the API, or the handler on the server.
Nevertheless, here's an example based on your snippet and JS's Promise/await combo:
setLoading(true)
const templates = await getTemplates(dispatch)
const delay = 1000;
await new Promise(resolve => setTimeout(resolve, delay));
setLoading(false);
Other example: node.js server
app.get('/api/whatever', (request, response) => {
const data = getDataFromDatabase():
const delay = 1000;
setTimeout(function() {
response.end(data);
}, delay);
})
Try this:
const call = (dati) => new Promise((resolve, reject) => {
setTimeout(() => { resolve(dati); }, 1000);
})
or you can see here: let promise wait a couple of seconds before return

ReactJS: how to make two backend requests at once?

Is it possible to make two backend requests at once from react?
The code below is the first backend call. The post request gets send to the backend and then I would like to do another request. Is it possible at all? Or do I have to wait for the backend response until the next request could be made?
What I basically want is to get information about how many files have been uploaded. The upload could take 3 minutes and the user right now only sees a loading icon. I want to additionally add a text like "50 of 800 Literatures uploaded" and 10 seconds later "100 of 800 litereratures uploaded".
This is basically my code :
class ProjectLiterature extends Component {
constructor(props) {
super(props);
this.state = {
isLoading:"false",
}
}
addLiterature(data, project_name) {
this.setState({ isLoading:true }, () => {
axios.post("http://127.0.0.1:5000/sendLiterature", data })
.then(res => {
this.setState({ isLoading: false })
})
})
}
If both requests do not depend on each other, you can make use of JavaScript's Promise.all() for the above purpose.
const request1 = axios.get('http://127.0.0.1:5000/sendLiterature');
const request2 = axios.get(url2);
Promise.all([request1,request2]).then([res1, res2] => {
// handle the rest
}).catch((error) => {
console.error(error);
// carry out error handling
});
If the second request relies on the response of the first request, you will have to wait for the first request to be completed as both requests have to be carried out in sequence.
const res = await axios.get('http://127.0.0.1:5000/sendLiterature');
// carry out the rest
You can see axios docs for this purpose, they support multiple requests out of box.
You can use Promise.all instead of axios.all as well but if one of requests fails then you won't be able to get response of successful calls. If you want get successful response even though some calls fails then you can use Promise.allSettled.

Redirect/ Routing issues in React and Express

I am creating a flight search app that makes external api calls. The data will be reorganized and returned in search results component.
On submit, the data is sent to express and takes about 10 seconds or more to complete all the api calls.
I think I need a loader at some point for during the delay of api calls, but also I am unsure of how to send/render the data.
As it stands, I have two pages home.js- '/' where i make the search and is sent to the server side, and prices.js- '/search' which when loaded fetches the data from the json file. but i do not have them connected
Both files work but I need to connect them. When I press submit, the user inputs are sent to server and the api calls are made but in order to see the results i have to manually refresh localhost:3000/search.
In express app after all the api calls, I tried res.redirect method, however the error given was setting the headers after sent to the client.
In react, I tried after submitting, to redirect to the search page. However I could not get it to redirect and also as soon as the /search page is called, it fetches the data from the file. This will happen before the api has finished writing to file and therefore the previous search results will render.
--in app.js
setTimeout(() => {
Promise.all([promise, promise2]).then(values => {
return res.redirect('http://localhost:3000/search');
});
}, 25000);
I had to wrap the api calls in promises so it will only redirect after all is written to file.
(in react prices.js)
componentDidMount() {
fetch('/search')
.then(res => {
return res.json()
})
.then(res => {
console.log(res.toString());
this.setState({flightData: res});
})
.catch(error => console.log(error));
}
home.js
home.js
```
onChange = (e) => {
this.setState({
originOne: e.target.value, originTwo: e.target.value});
};
onSubmit = (e) => {
e.preventDefault();
const { originOne, originTwo ,redirectToResult} = this.state;
};
```
app.js - I have all the functions calling each other in a waterfall style ( probably not the best way I know)
app.post('/', function getOrigins(req,res) {
var OrigOne;
var OrigTwo;
....
function IataCodeSearchOrg1(res, OrigOne, OrigTwo) {
...
findPrices(res,A,B)
}
function findPrices(res, A, B) {
promise = new Promise(function (resolve) {
...
}
}
All the methods are called within eachother. The api calls are in a loop and after each iteration they are written to the json file.
All these functions are in the app.post method and i tried to res.redirect but it did not work.
EDIT:
You can't redirect server-side from an XHR request. You would need to redirect client-side.
e.g.
componentDidMount() {
fetch('/search')
.then(res => res.json())
...
.then(() => window.location = '/myredirecturl')
}

Vue: Best practices for handling multiple API calls

So I found myself making more than one API call in my vuex action and this let me to wonder what would be the best way to hanfle this situatons, the best practices for multiple API calls, let's begin with the code I have.
I have an action where I gather all posts and all post categories from different API endpoints (laravel for backend), I'm sure there's have to be a better way t hanfle this than how I'm doing it:
fetchAllPosts ({ commit }) {
commit( 'SET_LOAD_STATUS', 1);
axios.get('/posts')
.then((response) => {
commit('FETCH_ALL_POSTS', response.data.posts )
commit( 'SET_LOAD_STATUS', 2 );
},
(error) => {
console.log(error);
commit( 'SET_LOAD_STATUS', 3 );
})
axios.get('/postcategories')
.then((response) => {
commit('FETCH_ALL_POSTCATEGORIES', response.data.postcategories )
commit( 'SET_LOAD_STATUS', 2 );
},
(error) => {
console.log(error);
commit( 'SET_LOAD_STATUS', 3 );
})
},
First issue with my approach that I can think of is if the first API call fails but the second succeeds I will get a load status of 2 (2 equals success here) !
I only want to procced with the commits if BOTH the first and second API call correctly fetch the data, please help someone who is learning.
I think you may want to read about promises.
On your example you are using Axios, which is a Promise based HTTP Client and that's great.
With Promises you can do several requests, and when all requests are successful you can THEN execute code.
With Axios you can do that with .all like this:
axios.all([getPosts(), getPostCategories()])
.then(axios.spread(function (posts, categories) {
// Both requests are now complete
}));
axios.all([
axios.get(firstUrl),
axios.get(secondUrl)
])
.then(axios.spread(function (response1, response2) {
//response1 is the result of first call
//response2 is the result of second call
}))
.catch(function (error) {
});
Note about catch(): It is called on the first failing request omitting the rest of the calls. So if the first call fails, catch() is called without even making the second request.

React Native Fetch won't execute

I've spent several hours trying to figure out how to query an API using fetch, but I can't even seem to get the fetch command to execute.
I'm very new to Javascript so hopefully someone can just point out some dumb mistake because I can't even get past the first step of using fetch.
Here is the very small snippet of code that I can't get to work.
var req = new Request('http://myapp.com:8000/api/posts', {method: 'GET'});
console.log("1");
fetch(req).then(function(res) {
console.log("2");
return res.json();
})
console.log("3");
The console logs "1", and "3", every time, but "2" is never even logged.
Does anyone know what is going on?
Also, I am making fetch requests to a locally running django server, and from monitoring the the server no requests are even being made to the server when I run my react-native app.
Try using fetch directly, see how it is done on the Networking page:
var url = 'http://myapp.com:8000/api/posts';
console.log("1");
fetch(url).then(function(res) {
console.log("2");
return res.json();
})
console.log("3");
Here is another way you can fetch data
fetch("http://date.jsontest.com/")
console.log("1");
.then((response) => response.json())
.then((responseData) => {
console.log("2");
this.setState({date: responseData.date});
})
.done();
}
Try adding a catch to check if there is any error.
fetch(url).then(function(res) {
console.log("2");
return res.json();
}).catch((error) => {
console.error(error);
});

Categories

Resources