Synchronous Actions
Async Actions
Our Application will fetch a list of users from an API endpoint and stores it in the redux store.
// typical form of state with data fetching
state = {
loading: true,
data: [],
error: ''
}
FETCH_USERS_REQUEST
- fetch list of users
FETCH_USERS_SUCCESS
- fetched successfully
FETCH_USERS_FAILURE
- Error fetching the data
const redux = require('redux'); // (4)
const createStore = redux.createStore; // (4)
// (1) define a state
const initialState = {
loading: false,
users: [],
error: ''
};
// (2) declare the constants for the action types and define action creators
const FETCH_USERS_REQUEST = 'FETCH_USERS_REQUEST';
const FETCH_USERS_SUCCESS = 'FETCH_USERS_SUCCESS';
const FETCH_USERS_FAILURE = 'FETCH_USERS_FAILURE';
const fetchUsersRequest = () => {
return {
type: FETCH_USERS_REQUEST
}
};
const fetchUsersSuccess = users => {
return {
type: FETCH_USERS_SUCCESS,
payload: users
}
};
const fetchUsersFailure = error => {
return {
type: FETCH_USERS_FAILURE,
payload: error
}
};
// (3) define reducer functions
const reducer = (state = initialState, action) => {
switch(action.type) {
case FETCH_USERS_REQUEST:
return {
...state,
loading: true
}
case FETCH_USERS_SUCCESS:
return {
loading: false,
users: action.payload,
error: ''
}
case FETCH_USERS_FAILURE:
return {
loading: false,
users: [],
error: action.payload
}
}
}
// (4) create a redux store
const store = createStore(reducer);