Understanding Custom Hooks and API Calls in React

in blurt •  last year 

Introduction:

In this blog post, we will explore a code snippet that demonstrates the usage of custom hooks and API calls in a React application. We'll break down the code and explain each part to provide a comprehensive understanding of how it works. Let's dive in!


src

Code Snippet:

import useToasterHook from "../useToasterHook";
import { useContext } from "react";
import { DashboradDataContext } from "../../store/contexts/DashboardDataContext";

export const useCommonApiCalls = () => {
  const pushNotification = useToasterHook();
  const { setApiResponseChangeMessage } = useContext(DashboradDataContext);

  const handleFilterListApiCall = (
    data,
    apiCallInfo,
    setOptionsList,
    setHideFilterOption,
    modifyFilterOptions,
    setCollegeId,
    setCounsellorListInternalServerError,
    setSomethingWentWrongInCounsellorList
  ) => {
    const { isSuccess, error, isError } = apiCallInfo;
    try {
      if (isSuccess) {
        if (Array.isArray(data)) {
          const listOfOptions = modifyFilterOptions
            ? modifyFilterOptions(data)
            : data;
          setOptionsList(listOfOptions);
          setCollegeId && setCollegeId(data[0]?.associated_colleges[0]);
        } else {
          throw new Error(
            "In counsellor wise filter college_counselor_list API response has changed"
          );
        }
      } else if (isError) {
        setHideFilterOption(true);
        if (error?.data?.detail === "Could not validate credentials") {
          window.location.reload();
        } else if (error?.data?.detail) {
          pushNotification("error", error?.data?.detail);
        }
        if (error.status === 500) {
          setHideFilterOption(true);
          setCounsellorListInternalServerError &&
            setCounsellorListInternalServerError(true);
        }
      }
    } catch (error) {
      setSomethingWentWrongInCounsellorList &&
        setSomethingWentWrongInCounsellorList(true);

      setApiResponseChangeMessage(error);
      setHideFilterOption(true);
    }
  };
  
  const handleExtraFilterListApiCall = (
    apiCallInfo,
    setHideExtraFilterList,
    setAllExtraFiltersList
  ) => {
    const { data, isSuccess, error, isError } = apiCallInfo;

    try {
      if (isSuccess) {
        if (Array.isArray(data.data)) {
          const modifiedResult = [];
          data.data.forEach((item) => {
            const tempData = {
              labelText: item.field_name,
              data: item.select_option.map((option) => ({
                label: option,
                value: {
                  field_name: item.field_name,
                  value: option,
                },
              })),
            };
            modifiedResult.push(tempData);
          });
          setAllExtraFiltersList(modifiedResult);
        } else {
          throw new Error(
            "In the lead manager, extra filter API response has changed"
          );
        }
      } else if (isError) {
        setHideExtraFilterList(true);
        if (error?.data?.detail === "Could not validate credentials") {
          window.location.reload();
        } else if (error?.data?.detail) {
          pushNotification("error", error?.data?.detail);
        }
        if (error.status === 500) {
          setHideExtraFilterList(true);
        }
      }
    } catch (error) {
      setApiResponseChangeMessage(error);
      setHideExtraFilterList(true);
    }
  };

  return { handleFilterListApiCall, handleExtraFilterListApiCall };
};

Explanation:

Importing Dependencies:

The code begins by importing the necessary dependencies for the functionality it provides. It imports a custom hook called useToasterHook from a specific file path. It also imports the useContext hook from React and the DashboradDataContext from a specific context file.


src

Custom Hook Usage:

The code defines a custom hook called useCommonApiCalls using the arrow function syntax. This hook encapsulates two functions: handleFilterListApiCall and handleExtraFilterListApiCall.

Extracting Custom Hooks:

Inside the useCommonApiCalls hook, the code utilizes the useToasterHook by calling useToasterHook() and assigning the returned value to the pushNotification constant. This hook is responsible for displaying toaster notifications in the application.

Accessing Context Data:

The code utilizes the useContext hook by calling useContext(DashboradDataContext) and extracting the setApiResponseChangeMessage function from the context. This allows the hook to access and modify data from the DashboradDataContext context.

Handling Filter List API Calls:

The handleFilterListApiCall function takes multiple parameters and is responsible for making API calls related to filtering lists. It checks the success or error status of the API call and performs specific actions accordingly. If the call is successful and the returned data is an array, it modifies the data if necessary and sets the options list. Additionally, it may set the college ID based on the data received. If the call results in an error, it handles different scenarios such as hiding filter options, reloading the page for authentication errors, and displaying error notifications. Internal server errors are also handled appropriately.

src

Handling Extra Filter List API Calls:

The handleExtraFilterListApiCall function is similar to handleFilterListApiCall but specifically handles API calls related to extra filter lists. It checks the success or error status of the API call and processes the data accordingly. If the call is successful and the returned data is an array, it modifies the data to a specific format and sets the extra filters list. Error handling includes hiding extra filter lists, page reloading for authentication errors, and displaying error notifications.

Conclusion:

In this blog post, we explored a code snippet that demonstrates the usage of custom hooks and API calls in a React application. We examined the functionality of the custom hooks useToasterHook and useCommonApiCalls. We also discussed how the code handles API call responses, modifies data if necessary, and performs error handling. By understanding this code, you can gain insights into building reusable hooks and handling API calls effectively in your React projects.

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE BLURT!