Api-integration
API
Judia react having fake-backend setup already. you will find
all files related
to api integrations in the src/helpers
folder. By default we have
provided
fake-backend but you can remove it and update with your custom API by doing the
following changes in the src/helpers
.
src/helpers/api_helper.ts
file contains axios setup to call server API(s) including get, put, post, delete, etc methods, interceptors & token set methods.-
src/helpers/fakebackend_helper.ts
file contain all API's call functions. -
src/helpers/url_helper.ts
file contain all module's API's url.
How to Integrate custom API?
Please follow the below steps :
-> Let's assume that our API's URL is
"https://jsonplaceholder.typicode.com/posts" .
First we have to add this URL in src/helpers/url_helper.ts
file
export const GET_DEMO_DATA = "https://jsonplaceholder.typicode.com/posts";
-> Whatever methods you want to use, import it import { APIClient } from
"src/helpers/api_helper";
and add below function in
src/helpers/fakebackend_helper.ts
file. We have created new function getDemoData and exported it so it can be used
in another files.
import { APIClient } from "./api_helper";
import * as url from "./url_helper"
const api = new APIClient();
export const getDemoData = (data: any) => api.create(url.GET_DEMO_DATA, data);
-> Reducer is also worked as middleware for react, which is placed
at
src/slices/ecommerce/reducer.ts
file. we can get data in reducer from thunk.ts
file.
import { createSlice } from "@reduxjs/toolkit";
import { getData } from "./thunk"
export const initialState ={
dataList: [],
}
const EcommerceSlice = createSlice({
name : "Data",
initialState,
reducers: {},
extraReducers: (builder) => {
//data
builder.addCase(getData.fulfilled, (state: any, action: any) => {
state.dataList = action.payload;
});
builder.addCase(getData.rejected, (state: any, action: any) => {
state.error = action.payload.error || null;
});
},
})
-> A thunk works as a middleware, which is placed at
src/slices/Data/thunk.ts
folder. We have to import api from the fakebackend_helper.ts
file.
import { createAsyncThunk } from "@reduxjs/toolkit";
import {
getData as getDataApi,
} from "src/helpers/fakebackend_helper"
export const getData = createAsyncThunk("datas/getData", async () => {
try {
const response = getDataApi();
return response;
} catch (error) {
return error;
}
});
-> After following the above steps you can call data and use it in your components or pages where is needed by the dispatch data method and managing the state.
import { getData as onGetData} from "slices/thunk";
const datasTable = createSelector(
(state : any) => state.Data,
(state) => ({
dataList: state.dataList,
})
);
const { dataList } = useSelector(datasTable);
useEffect(() => {
dispatch(onGetData())
}, [dispatch]);