0

I made a function to get request. It look like this

export const toggleCompleted  = (id) => {
    axiosMethod.get('api/taks/toggle/' + id)
               .then(res => {
                   console.log(res.data)
                  return res.data;
               }).catch(error => {
                   return error;
               })
    return 'Test';
}

I want to get this request and if PHP return true, run dispatch. So I made this code

const markAsCompleted = (id) => {
    console.log(toggleCompleted(id));
    if (toggleCompleted(id) == 1){
        toggleMarkAsCompleted(id);
    }
   

}

toggleCompleted is a my request which is show before toggleMarkAsCompletedis my dispatch. If toggleCompleted return 1 I want to run my dispatch. It's simple? Interested is that this code

console.log(toggleCompleted(id));

return Test while my request 1 or 0 (from .then()). Why?

  • `toggleCompleted` doesn't `return` anything – Bravo Sep 03 '21 at 04:56
  • Does this answer your question? [How to return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – SuperStormer Sep 03 '21 at 05:38

1 Answers1

0

Add return in the toggleCompleted and use async/await to get return data

export const toggleCompleted = (id) => {
  return axiosMethod
    .get("api/taks/toggle/" + id)
    .then((res) => {
      console.log(res.data);
      return res.data;
    })
    .catch((error) => {
      return error;
    });
};

const markAsCompleted = async (id) => {
  const res = await toggleCompleted(id);
  if (res == 1) {
    toggleMarkAsCompleted(id);
  }
};
Viet
  • 12,133
  • 2
  • 15
  • 21