D
D
DarthJS2018-04-02 11:30:30
React
DarthJS, 2018-04-02 11:30:30

What is the best way to write Reducer and Action in this situation?

There is a state , for example cats , when adding a new cat I pull the ADD_NEW_CAT action .
But, when updating, updating the application, or initializing, I make a request to the server and upload all the data, it so happened historically that an array object comes with the request:

response: {
cats: [ , , ,],
dogs: [ , , ,],
hozyainy: [],
}

I do ACTION LOAD_DATA where I return this data.
In Reducer, I have no choice but to save the entire object in state .
How can the incoming data be divided into different states ?
That is, so that at LOAD_DATA I have three arrays loaded from the server. And when adding a new cat || dog did they get into the corresponding state ? At the moment the situation is as follows:state: {cats: [], dogs: [], hozyiny: [] }

state: {
loadedData: {cats: [], dogs: [], hozyiny: []},
cats: [],
dogs: [],
hozyiny: [],
}

CODE:
ACTIONS:
export const loadAllData = (response) => { 
return {
    type: 'LOAD_ALL_DATA',
    data: response,
}};

export const getAllData = () => async (dispatch, getState) => {

    const storedData = JSON.parse(localStorage.getItem('data'));
    if (storedData) {
        dispatch(loadAllData(storedData));
    } else {
    try {
        const response = await Api.getAllData();
        localStorage.setItem('data', JSON.stringify(response));
        dispatch(loadAllData(response));
    } catch (error) {
        console.error(error);
    }
    }
}

REDUCER:
export const loadedData = (state = [], action) => {
    switch (action.type) {
        case 'LOAD_ALL_DATA':
            return action.data;     // Как разбить данные в разные стейты?
        default:
        return state;
    }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Alekseev, 2018-04-03
@DarthJS

DarthJS , In any case, the reducers will have their own names in the state. If an object of this kind { cats: [], dogs: [], ... } comes to action.data, then I would do this.

const initialState = {
  cats: [],
  dogs: [],
  hozyiny: []
}

const reducer = (state = initialState, action) => {
  switch(action.type) {
    case LOAD_ALL_DATA: {
      const { cats, dogs, hozyiny } = action.data;
      return Object.assign({}, state, { cats, dogs, hozyiny })
    }
    default:
      return state
  }
}

B
BugsCreator, 2018-04-02
@BugsCreator

If I understood the question correctly
In reducer:

case 'LOAD_ALL_DATA':
  return {
  ...state,
  cats: action.cats,
  dogs: action.dogs,
  hozyiny: action.hozyiny
  }

In action:
export const loadAllData = (response) => { 
  return {
    type: 'LOAD_ALL_DATA',
    cats: response.cats,
    dogs: response.dogs,
    hozyiny: response.hozyiny
  }};

The store itself in the reducer:
state: {
  cats: [],
  dogs: [],
  hozyiny: [],
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question