1.0.3 • Published 7 months ago

generate-api-slice-thunk v1.0.3

Weekly downloads
-
License
MIT
Repository
-
Last release
7 months ago

generate-api-slice-thunk

A utility to generate Redux Toolkit slices and async thunks for API requests.

Installation

npm install generate-api-slice-thunk

Usage

import generateApiSliceAndThunk from 'generate-api-slice-thunk';

Step to create files

1- Create a folder in src and name it "Networking"

2- Create a folder inside "Networking" folder for example you want to handle user related slices so you have to create folder with name "User"

3-Create a file inside "User" folder and name it "userServices.js"

4-Inside "userServices.js" do this as bellow!

import generateApiSliceAndThunk from 'generate-api-slice-thunk';

const {slice: loginSlice, request: loginThunk} = generateApiSliceAndThunk( 'loginSlice', { endPoint: '/login', method: 'post', tokenRequired: false, isMultiPart: false, }, async (params, options) => { const { endPoint, method, tokenRequired, isMultiPart } = options

const baseUrl='example.com/'
const response = await fetch(baseUrl+endPoint, params);
return response.json();

} );

export {loginSlice, loginThunk};

Step to call api

1- Create a component name it "DummyScreen.js"

2-Inside "DummyScreen.js" component simply dispatch the action like

import {loginThunk} from 'your own path for loginThunk';

const dispatch = useDispatch(); const loginHandler = async () => { dispatch(loginThunk({ username:'wazirkhan250@gmail.com' password:'wazir@78' })) .then(response => { if (response?.payload) { console.log('This is final api response', response?.payload); } }) .catch(error => { console.log(error); return; }); };

3-This is it for simple calling api and getting the final api response but if you want to persist the data as well you have to pass the reducer in combineReducer while setting up your store for example

const rootReducer = combineReducers({ loginSlice: loginSlice.reducer, //do not forget to import "loginSlice"

});

4-Now by using persist store configration and passing "rootReducer" to it , whenever user will hit loginApi call data will be stored in "Store"

Step to get data from store

1- We can get data as we normally get state from store by using useSelector

const {data: user} = useSelector(state => state?.loginSlice);

console.log(user)

Important Note

You can pass your own function as a callBack function in "generateApiSliceAndThunk" and manage your api calls in it

Feel free to contact at Wazirkhan250@gmail.com incase you guys have any confusion

Thank you

1.0.3

7 months ago

1.0.2

7 months ago

1.0.1

7 months ago

1.0.0

7 months ago