In Tailwick React, a fake backend setup is included by default. All the files related to API
integrations can be located within the
src/helpers
folder. While we've provided a fake backend for
your convenience,
you have the flexibility to remove it and replace it with your custom API by following the
steps outlined in the
src/helpers
directory.
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.
src/helpers/fakeBackend.ts
, and remove the code related to
Fake-Backend from
app.ts
file. you just need to update API's URL of the related
module in the
src/helpers/url_helper
file,
that's it!
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.get(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) => {
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]);