score:0

AsyncFunction is returning a function, not the data that comes from the API call. What you can do, if I understand your problem correctly, is return the response from the call and remove the initial return statement.

score:1

You can do the same process without returning the function and directly completing the process in it.

Change the use effect code as follows:

useEffect(() => {
    (async () => {
      await asyncFunction(dispatch);
      // do stuff
    })();
  }, []);
const asyncFunction = async (dispatch, data) => {
    try {
      const response = await APICall();
      dispatch({ type: "search", payload: response.data });
    }
    // error handling
}

Because in the function you mentioned you are dispatching data to reducer and not returning the data. So instead you can just do the processing work there.

In case you want to return some data, you can refer the code below:

Previous Code:

const asyncFunction = (dispatch, data) => {
  return new Promise((resolve, reject) => {
    APICall()
      .then((reponse)=>{
        dispatch({ type: "search", payload: response.data });
        //This will return value to the calling function. This will act as a return statement
        resolve(response);
      })
      .catch((err)=>{
        //This will be executed if there is any error.
        reject(err)
      })
  })

Changed Code (as @Bergi said to avoid Promise constructor anti-pattern):

useEffect(() => {
    let mounted = true;
    APICall()
        .then((response) => {
            if (mounted) {
                dispatch({ type: "search", payload: response.data });
                //do some stuff here
            }
        })
        .catch((err) => {
            //handle error here
        })
    return () => mounted = false;
}, []);

Promises would be the best way to return data from async function.

score:1

I could be totally wrong, but I think that you might be running into issues returning the async function, explained here in docs.

Also, it looks like you might be calling asyncFunction (inside your useEffect hook) without a value for dispatch? Here:

  (async () => {
      await asyncFunction();
      // do stuff

I regurgitated a custom hook for API calls following your plan: link to sandbox. Hopefully it can be helpful!


Related Query

More Query from same tag