Home > Mobile >  converting custom react function to async
converting custom react function to async

Time:11-29

I made this custom hook.

import axios from "axios";
import Cookies from "js-cookie";
import React from "react";
const useGetConferList= () => {
  let token = JSON.parse(localStorage.getItem("AuthToken"));
  const Idperson = JSON.parse(Cookies.get("user")).IdPerson;
  const [response, setResponse] = React.useState();
  const fetchConfer= (datePrensence, idInsurance, timePrensence) => {
    axios({
      method: "post",
      url: `${process.env.REACT_APP_API_URL_API_GET_ERJASERVICE_LIST}`,
      headers: {
        Authorization: `Bearer ${token}`,
        "Content-Type": "application/json",
      },
      data: JSON.stringify({
        datePrensence,
        idInsurance,
        Idperson,
        searchfield: "",
        timePrensence: parseInt(timePrensence) * 60,
      }),
    })
      .then((r) => {
        setResponse(r.data.Data);
      })
      .catch(() => alert("NetworkError"));
  };
  return { fetchConfer, response };
};

export default useGetConferList;

as you can see I export the fetchConfer function. but I want to make it async. for example, calling the function and then doing something else like this:

fetchConfer(Date, Time, Id).then((r) => {
      if (search !== "") {
        window.sessionStorage.setItem(
          "searchList",
          JSON.stringify(
             r.data
          )
        );
      }
});

as you can see in non async situation, I can't use then.

CodePudding user response:

Just return the axio call inside the function

 const fetchConfer= (datePrensence, idInsurance, timePrensence) => {
     return  axios({
               method: "post",
    ......

CodePudding user response:

You can try this

 const fetchConfer = async (datePrensence, idInsurance, timePrensence) => {
    try {
      const response = await axios({
        method: "post",
        url: `${process.env.REACT_APP_API_URL_API_GET_ERJASERVICE_LIST}`,
        headers: {
         Authorization: `Bearer ${token}`,
         "Content-Type": "application/json",
        },
        data: JSON.stringify({
         datePrensence,
         idInsurance,
         Idperson,
         searchfield: "",
         timePrensence: parseInt(timePrensence) * 60,
        }),
     })

     setResponse(response.data.Data);
     // need to return data
     return response.data.Data

    } catch(error) {
      alert("NetworkError")
    }
  };

use the function in another async function

const someAsyncFunc = async () => {
   // try catch 
   const r = fetchConfer(Date, Time, Id)
   if (search !== "") {
        window.sessionStorage.setItem(
          "searchList",
          JSON.stringify(
             r.data
          )
        );
   }
  ...

or use it how you are currently using it

Hope it helps

  • Related