DEV Community

MERN Practical Explanation
MERN Practical Explanation

Posted on

Axios Filter Map live exampe

Certainly! Let's break down the FetchSlots function and explain its structure:

const FetchSlots = () => {
    try {
        // Step 1: Prepare request object with business_id set to 0
        let obj = {
            business_id: 0,
        };

        // Step 2: Make a POST request using axios
        axios
            .post(`${baseUrl}api/v1/appointment/FetchSlots`, obj, {
                headers: {
                    _token: userData?.token,
                },
            })
            .then((response) => {
                // Step 3: Extract unique business titles from response data
                let tempArr = response?.data?.data?.records?.filter((el) => el?.businessTitle !== '' && el?.businessTitle !== undefined)
                    .map((el) => el.businessTitle);

                let tempUniqueArr = new Set(tempArr);
                tempUniqueArr = [...tempUniqueArr];

                // Step 4: Set unique business titles to state variable 'setBusinessData'
                setBusinessData(tempUniqueArr);

                // Step 5: Extract and format relevant data from response
                let newDataArray = [];
                response?.data?.data?.records.forEach(rs => {
                    rs?.slots?.forEach(rss => {
                        if (rss?.startDate !== '' && rss?.endDate !== '') {
                            let newData = {
                                id: `${rs?.id}_${rs?.business_id}_${rss?.formCount}`,
                                business_id: rs?.business_id,
                                businessTitle: rs?.businessTitle,
                                formCount: rss?.formCount,
                                startDate: rss?.startDate,
                                endDate: rss?.endDate,
                                status: rss?.status || 'NA',
                            };
                            newDataArray.push(newData);
                        }
                    });
                });

                // Step 6: Set formatted data to state variables 'setTempData' and 'setData'
                setTempData(newDataArray);
                setData(newDataArray);
                setIsLoading(false);
            })
            .catch((error) => {
                // Step 7: Handle errors
                setIsLoading(false);
            });
    } catch (err) {
        // Step 8: Handle any synchronous errors
        console.log(err, "erroror");
    }
};
Enter fullscreen mode Exit fullscreen mode

Explanation:

  1. Preparing Request Object: The function starts by creating an object obj with business_id set to 0.

  2. Making POST Request: Axios is used to make a POST request to a specific API endpoint (${baseUrl}api/v1/appointment/FetchSlots). The request includes the obj data and a header with the authorization token (_token) from userData.

  3. Handling Response: In the .then block, the function processes the response data.

a. Extracting Unique Business Titles: It filters and maps business titles, removing empty or undefined values, and then uses a Set to get unique values.

b. Setting Business Data to State: The unique business titles are set to the state variable setBusinessData.

c. Formatting Data: The function extracts relevant data from the response, including id, business_id, businessTitle, formCount, startDate, endDate, and status. This data is formatted into a new array newDataArray.

d. Setting State Variables: The formatted data is set to state variables setTempData and setData.

  1. Handling Errors: In the .catch block, any errors that occur during the HTTP request are handled, and the loading state (setIsLoading) is updated accordingly.

  2. Handling Synchronous Errors: Any synchronous errors (outside the axios block) are caught in the try-catch block, and an error message is logged.

Note: Ensure that the variables like baseUrl, axios, setBusinessData, setTempData, setData, and setIsLoading are defined and accessible in the scope where this function is used.

Certainly! Let's break down and explain the fetchApppointent function:

const fetchApppointent = (page) => {
    try {
        // Step 1: Log a message indicating the function is being executed
        console.log("In fetchApppointent api");

        // Step 2: Prepare the request object with business_id and filters
        let obj = {
            business_id: businessObjData?.id || "2",
        };

        // Step 3: Format start and end dates if available
        const formattedStartDate = selectedDateFrom ? format(new Date(selectedDateFrom), 'yyyy-MM-dd') : null;
        const formattedEndDate = selectedDateTo ? format(new Date(selectedDateTo), 'yyyy-MM-dd') : null;

        // Step 4: Prepare filters object based on selected dates and active business name
        const filters = {
            startDate: formattedStartDate,
            endDate: formattedEndDate,
            business: activeBusinessName === "All Business" ? null : activeBusinessName,
        };

        // Step 5: Make a POST request using axios to fetch appointments with pagination
        axios
            .post(`${baseUrl}api/v1/appointment/FetchAppointments_withpagination?page=${page}&limit=${rowsPerPage}`, { ...obj, ...filters }, {
                headers: {
                    _token: userData?.token,
                },
                withCredentials: true,
            })
            .then((response) => {
                // Step 6: Extract unique business titles from response data
                let tempArr = response?.data?.data?.records?.map(
                    (el) => el?.businessTitle
                );
                let tempUniqueArr = new Set(tempArr);
                tempUniqueArr = [...tempUniqueArr];

                // Step 7: Set unique business titles to state variable 'setBusinessData'
                setBusinessData(tempUniqueArr);

                // Step 8: Sort and set the response records based on created_at date
                let arr = response?.data?.data?.records;
                arr = arr.sort(
                    (x, y) => new Date(y?.created_at) - new Date(x?.created_at)
                );

                // Step 9: Set the sorted data to state variables 'setTempData' and 'setData'
                setTempData(arr);
                setData(arr);

                // Step 10: Set total rows for pagination
                setPaginationTotalRows(response?.data?.pagination?.totalCount);

                // Step 11: Log the total count of appointments for debugging
                console.log("ttl ap", response?.data?.pagination?.totalCount);

                // Step 12: Set loading state to false
                setIsLoading(false);
            })
            .catch((error) => {
                // Step 13: Handle errors and set loading state to false
                setIsLoading(false);
            });
    } catch (err) {
        // Step 14: Handle any synchronous errors and log an error message
        console.log(err, "erroror");
    }
};
Enter fullscreen mode Exit fullscreen mode

Explanation:

  1. Logging Message: The function starts by logging a message to the console to indicate that it is being executed.

  2. Preparing Request Object: The function creates an object obj with business_id based on the value of businessObjData?.id or a default value of "2".

  3. Formatting Dates: The selected start and end dates are formatted using the format function (assuming it's from a date formatting library, possibly date-fns).

  4. Preparing Filters Object: The function creates a filters object based on the formatted start and end dates and the active business name.

  5. Making POST Request: Axios is used to make a POST request to a specific API endpoint (${baseUrl}api/v1/appointment/FetchAppointments_withpagination). The request includes the merged obj and filters objects, and it includes headers and credentials information.

  6. Handling Response: In the .then block, the function processes the response data.

a. Extracting Unique Business Titles: Unique business titles are extracted from the response data.

b. Setting Business Data to State: Unique business titles are set to the state variable setBusinessData.

c. Sorting Data: The response records are sorted based on the created_at date in descending order.

d. Setting State Variables: The sorted data is set to state variables setTempData and setData.

e. Setting Total Rows for Pagination: The total count of appointments for pagination is extracted and set to the state variable setPaginationTotalRows.

f. Logging Total Count: The total count of appointments is logged for debugging.

g. Setting Loading State: The loading state is set to false.

  1. Handling Errors: In the .catch block, any errors that occur during the HTTP request are handled, and the loading state (setIsLoading) is updated accordingly.

  2. Handling Synchronous Errors: Any synchronous errors (outside the axios block) are caught in the try-catch block, and an error message is logged.

Note: Ensure that the variables like baseUrl, axios, setBusinessData, setTempData, setData, setPaginationTotalRows, setIsLoading, businessObjData, selectedDateFrom, selectedDateTo, activeBusinessName, userData, rowsPerPage, and format are defined and accessible in the scope where this function is used.

Top comments (0)