Answer the question
In order to leave comments, you need to log in
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: [],
}
state: {cats: [], dogs: [], hozyiny: [] }
state: {
loadedData: {cats: [], dogs: [], hozyiny: []},
cats: [],
dogs: [],
hozyiny: [],
}
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);
}
}
}
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
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
}
}
If I understood the question correctly
In reducer:
case 'LOAD_ALL_DATA':
return {
...state,
cats: action.cats,
dogs: action.dogs,
hozyiny: action.hozyiny
}
export const loadAllData = (response) => {
return {
type: 'LOAD_ALL_DATA',
cats: response.cats,
dogs: response.dogs,
hozyiny: response.hozyiny
}};
state: {
cats: [],
dogs: [],
hozyiny: [],
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question