API Integration

Chaton react having fake-backend setup already. you will find all files related to API integrations in the src/helpers folder.

  • src/helpers/api_helper.ts file contains axios setup to call server API(s) including get, put, post, patch, delete, etc methods, interceptors & token set methods.

  • src/helpers/fakebackend_helper.ts file contain all module's API call functions which are exported from each module's individual .ts file, E.g. contacts.ts, bookmarks.ts etc.

  • src/helpers/url_helper.ts file contain all module's API's url.

Note : we have added a Fake backend setup just for user interactions, but if you are working with the real API integration, then there is no need of fake backend as well as the fakeBackend file located in src/helpers/fakebackend_helper.ts, so you can delete it and also remove the code related to fakeBackend from app.tsx file. you just need to update API's url of the related module from src/helpers/url_helper.ts file, that's it!
How to Integrate custom API?

Please follow the below steps to make the custom API working.

  1. let's assume that our API's url is "..baseurl/user-profile-details/{userId}". so implement it, first we have to add this url in src/helpers/url_helper.ts file, so open the file and add the following code.
    ...
    export const USER_PROFILE_DETAILS = "/user-profile-details";
  2. if this is a new module of your app, then create a new .ts file in src/helpers/ folder named userProfile.ts and write following code in it.
    import * as url from "./url_helper";
    import { del, get, post, put } from "./api_helper";
    
    const getUserProfile = () => get(url.USER_PROFILE_DETAILS);
                    
    export { getUserProfile };
    
    do not forget to export newly created file's content (userProfile.ts) in index.ts file, let's do this.
    ...
    export * from "./userProfile";
    
  3. After the above setup, We will do redux action's setup. Please check How To Create Actions & Thunk first.

    Create a folder named with your module in src/slices folder i.e. demo module then it should be src/slices/demo then create actions.ts, Thunk.ts, reducer.ts & actionTypes.ts files and follow the pattern of other modules which are added in this template. Also do not forget to export it in main files (actions.ts, reducers.ts and Thunk.ts ) of src/slices folder.

  4. Add your action name in the actionTypes.ts file. E.g.
    export const USER_PROFILE_DETAILS = "/get/user-profile-details";
    
  5. Create the action in the action.ts file. And make sure you pass the same action type as a type parameter which you added in actionTypes.ts file.
    import { APIClient } from "./api_helper";
    import * as url from "./url_helper";
    
    export const getUserProfile = () => api.get(url.USER_PROFILE_DETAILS, null);
    
  6. Add your action to the reducer.ts as well. Here, we can have either success or error response from the API. so we will manage this by API_RESPONSE_SUCCESS & API_RESPONSE_ERROR actions.
    import { createSlice } from "@reduxjs/toolkit";
    import {getUserProfile} from './thunk';
    
    export const initialState = {
      userProfile: [],
      error: {}
    };
    
    const User = createSlice({
      name: 'userProfileSlice',
      initialState,
      reducers: {},
      extraReducers: (builder) => {
          builder.addCase(getUserProfile.fulfilled, (state: any, action: any) => {
              state.userProfile = action.payload;
          });
    
          builder.addCase(getUserProfile.rejected, (state: any, action: any) => {
              state.error = action.payload.error || null;
          });
      }
    })
    
    export default User.reducer;
    
  7. Now, create Thunk.ts file and Add Thunk funtion & watchers for the action.
    import { createAsyncThunk } from "@reduxjs/toolkit";
    
    import {getUserProfile as getUserProfileApi} from "../../helpers/fakebackend_helper";
    
    export const getUserProfile = createAsyncThunk("profile/getUserProfile", async () => {
        try {
            const response = getUserProfileApi();
            return response;
        } catch (error) {
            return error;
        }
    });
  8. After redux & Thunk's setup, you just need to call the action from your component. E.g.
    import React, { useEffect } from "react";
    import { createSelector } from 'reselect';
    
    //redux
    import { useSelector, useDispatch } from "react-redux";
    
    // actions
    import { getUserProfile } from "../slices/thunk";
    
    const UserData = (props: any) => {
      const dispatch = useDispatch();
    
      const selectLeadData = createSelector(
          (state: any) => state.User,
          (user) => ({
            userProfile: user.userProfile,
          })
      );
      const { userProfile } = useSelector(selectLeadData);
    
      /*
      get data
      */
      useEffect(() => {
        dispatch(getUserProfile());
      }, [dispatch]);
    
      // your API's response data will be in events variable.
      console.log(userProfile);
    
      return (
        <div>
        </div>
      );
    };
    
    export default UserData;
© Themesbrand.
Crafted with by Themesbrand