Api-integration
API
Steex 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.tsfile contains axios setup to call server API(s) including get, put, post, delete, etc methods, interceptors & token set methods.-
src/helpers/fakebackend_helper.tsfile contain all API's call functions. -
src/helpers/url_helper.tsfile 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 getDemoData = () => api.get(url.GET_DEMO_DATA);
export { getDemoData };
create reducer.ts file, Reducers are used in APIs to manage the state of the API.
They are typically used in conjunction with the getState and dispatch methods, which allow you to
get the current state of the API and dispatch an action to the API, respectively.
import { createSlice } from "@reduxjs/toolkit";
export const initialState = {
forgetSuccessMsg: null,
forgetError: null,
};
const demoSlice = createSlice({
name:"",
initialState,
reducers:{
demoSuccess(state, action) {
state.forgetSuccessMsg = action.payload
},
demoError(state, action) {
state.forgetError = action.payload
},
},
});
export const {
demoSuccess,
demoError
} = demoSlice.actions
export default demoSlice.reducer;
Create thunk.ts file , Thunk is used for APIs because it allows you to perform
asynchronous operations, such as making HTTP requests, within the context of a Redux action. This is
useful because it allows you to keep your Redux state consistent and predictable, even when you are
making asynchronous requests .
import { demoSuccess, demoError } from "./reducer"
const demoData = () => async(dispatch) => {
try {
let response;
const data = await response;
if (data) {
dispatch(demoSuccess(
"message"
))
} catch (forgetError) {
dispatch(demoError(forgetError))
}
}
}
export default demoData;