To create an action creator that triggers a loading spinner during an async operation:
1. Define Action Types:
const FETCH_START = 'FETCH_START';
const FETCH_SUCCESS = 'FETCH_SUCCESS';
const FETCH_FAILURE = 'FETCH_FAILURE';
2. Create Action Creators:
export const fetchStart = () => ({ type: FETCH_START });
export const fetchSuccess = (data) => ({ type: FETCH_SUCCESS, payload: data });
export const fetchFailure = (error) => ({ type: FETCH_FAILURE, payload: error });
3. Async Operation using redux-saga:
import { call, put } from 'redux-saga/effects';
import { fetchStart, fetchSuccess, fetchFailure } from './actions';
function* fetchDataSaga() {
yield put(fetchStart()); // Show loading spinner
try {
const data = yield call(apiCall); // API request
yield put(fetchSuccess(data)); // Hide spinner + show data
} catch (error) {
yield put(fetchFailure(error)); // Hide spinner + show error
}
}
4. Handle Loading State in Reducer:
const initialState = {
loading: false,
data: null,
error: null,
};
function dataReducer(state = initialState, action) {
switch (action.type) {
case FETCH_START:
return { ...state, loading: true, error: null };
case FETCH_SUCCESS:
return { ...state, loading: false, data: action.payload };
case FETCH_FAILURE:
return { ...state, loading: false, error: action.payload };
default:
return state;
}
}