How to create an action creator that triggers a loading spinner during an async operation

0 votes
With the help of proper code example can you tell me How to create an action creator that triggers a loading spinner during an async operation?
Mar 19 in Node-js by Ashutosh
• 24,010 points
56 views

1 answer to this question.

0 votes

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;

  }

}

answered Mar 24 by anonymous

Related Questions In Node-js

0 votes
0 answers
0 votes
0 answers
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

How to differentiate between takeLatest and takeEvery in redux-saga?

Feature takeEvery takeLatest Execution Behavior Executes every triggered action. Executes only the ...READ MORE

answered Mar 24 in Node-js by anonymous
48 views
0 votes
1 answer
0 votes
1 answer

How to integrate redux-saga middleware into a React project?

To integrate redux-saga middleware into a React ...READ MORE

answered Mar 24 in Node-js by anonymous
48 views
0 votes
1 answer
0 votes
1 answer

How to create an action creator for fetching data in Redux?

To create an action creator for fetching ...READ MORE

answered Mar 18 in Node-js by Anvi
45 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP