Answer the question
In order to leave comments, you need to log in
What should be contained in the reducer or where should the functionality be stored?
Good day. React native app with redux. There is a set of actions. There is a set of gearboxes. And there is a function that causes state changes, that is, "action". Everything seems to be clear here.
export const endOrderCreateAction = (dispatch, orderStatus) => {
return {
type: END_ORDER_CREATE,
orderStatus: orderStatus
}
};
.........
const orderReducer = (state = {data: [], loading: false}, action) => {
switch(action.type) {
case END_ORDER_CREATE:
return {...state, loading: true};
...........
fetch().then(r => dispatch(endOrderCreateAction(dispatch, r)));
fetch().then(r => {
dispatch(endOrderCreateAction(dispatch, r));
dispatch(stopLoadingAction(dispatch, r));
....
});
const orderReducer = (state = {data: [], loading: false}, action) => {
switch(action.type) {
case END_ORDER_CREATE:
..........
const loadingReducer = (state = {data: [], loading: false}, action) => {
switch(action.type) {
case END_ORDER_CREATE:
case END_USER_LOADING:
case END_SECTION_LOADING:
..........
// одно изменение состояния ловят сразу несколько редукторов
const orderReducer = (state = {data: [], loading: false}, action) => {
switch(action.type) {
case END_ORDER_CREATE:
return {...state, loading: false}
// собираем итоговый state
state = {
loading: orderReducer.loading || sectionReducer.loading || userReducer.loading
}
Answer the question
In order to leave comments, you need to log in
In general, there are several solutions.
As an option, to start with, use one loading field for the store and call a separate action before network calls, for example
// todo/actions.js
export const getTodos = (dispatch) => () => {
dispatch({ type: 'GET_TODOS_REQUEST' });
return fetch('/api/v1/todos')
.then((todos) => dispatch({ type: 'GET_TODOS_SUCCESS', payload: todos })
.catch((error) => dispatch({ type: 'GET_TODOS_FAILURE', payload: error, error: true });
};
// todo/reducer.js
const initialState = { todos: [] };
export const todoReducer = (state = initialState, action) => {
switch(action.type) {
case 'GET_TODOS_REQUEST':
return { ...state, isFetching: true };
case 'GET_TODOS_SUCCESS':
return { ...state, isFetching: false, todos: action.payload };
case 'GET_TODOS_FAILURE':
return { ...state, isFetching: false, errorMessage: action.payload.message };
default:
return state;
}
};
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question