Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Promises in React native

Tags:

api/index.js

const URL = 'http://10.0.2.2:5000';
const fetching = false;

export default (type, filter, dateFilter, position) => {
    if(fetching) return Promise.reject(new Error('Request in progress'));
    fetching = true;
    return fetch(URL + `/search/${type}/${filter}/${dateFilter}/${position}/0/0`)
    .then(response => Promise.all([response, response.json()]))
    .catch(err => console.log("error catch search:", err.message))

}

I need to put fetching false so in that way i can call this function again, but i dont know where to put it to make it work. If i create another then like this after the then writen and before the catch like this:

.then(() => fetching = false)

The problem is that it returns false to the place the function is called and NOT the data this is where is called:

actions/index.js

getDataApi(type, filter, dateFilter, position)
   .then(res => {   
     if (res !== false) {         
         if (state.dataReducer.data.length === 0) {
             dispatch(getDataSuccess(res[1]))
         } else {
             dispatch(getDataSuccess(res[1], state.dataReducer.data))
         }       
    }
 })
.catch((err) => console.log(9999, err))

So my problem is that it doesnt enter in the getDataSuccess because is false.I dont know why it cannot send the data to this function and it ends sending the result of fetching = false.

like image 639
Franco Coronel Avatar asked Jun 29 '18 01:06

Franco Coronel


1 Answers

You need another .then so that you can reassign fetching after the response.json() resolves. You should also probably reassign fetching in the catch so that future requests are possible even if there's an error once, and return false in the catch so the .then after getDataAPI will properly ignore failed requests. Also, use let rather than const for fetching:

const URL = 'http://10.0.2.2:5000';
let fetching = false;

export default (type, filter, dateFilter, position) => {
  if (fetching) return Promise.reject('Request in progress');
  fetching = true;
  return fetch(URL + `/search/${type}/${filter}/${dateFilter}/${position}/0/0`)
    .then(response => Promise.all([response, response.json()]))
    .then(([response, responseObj]) => {
      fetching = false;
      return [response, responseObj];
    })
    .catch(err => {
      console.log("error catch search:", err.message);
      fetching = false;
      // Choose one, depends what you need.
      return false; // If you want to ignore the error and do something in a chained .then()
      return Promise.reject(err); // If you want to handle the error in a chained .catch()
    })
}
like image 168
CertainPerformance Avatar answered Sep 19 '22 04:09

CertainPerformance