user2903536 user2903536 - 2 months ago 22
React JSX Question

Want to return different value from same reducer in reactjs

import {FETCH_OBSERVATION} from '../actions/index';
import {DELETE_OBSERVATION} from '../actions/index';

export default function(state={all:[],count:null},action){
switch (action.type) {
case FETCH_OBSERVATION:
console.log("data for fetch observationCount",action.payload.data.model.observationInstanceList);

return{
all:state.all.concat(action.payload.data.model.observationInstanceList),
count:action.payload.data.model.observationCount
}
case DELETE_OBSERVATION:
return state.all=[];
default:
return state

}
return state;
}


I am fetching data from the API using action creator define in action/index file.
Can Anybody told me why state.all.concat is not defined ?

the error look something like this

Cannot read property 'concat' of undefined
at ./src/reducers/reducer_observation.js.__webpack_exports__.a (reducer_observation.js:10)
at combination (combineReducers.js:120)
at dispatch (createStore.js:165)
at redux-logger.js:1
at index.js:28
at dispatch (applyMiddleware.js:35)
at action.payload.then._extends.payload (index.js:25)
at <anonymous>


My Combine Reducer look like this

import { combineReducers } from 'redux';
import SpeciesChartReducer from './reducer_chart_data';
import ObservationReducer from './reducer_observation';
import TaxonReducer from './reducer_taxon_list';
import UserGroupNames from './reducer_fetch_userGroup';
import UserGroupObservations from './reducer_fetch_groupobservations';
import HomeTotalCount from './reducer_home_total_count';

const rootReducer = combineReducers({
Observation:ObservationReducer,
ChartData:SpeciesChartReducer,
treeData:TaxonReducer,
UserGroupNames:UserGroupNames,
UserGroupObservations:UserGroupObservations,
HomeTotalCount:HomeTotalCount
});

export default rootReducer;

Answer Source

ok, so if u want above function to work, then do like this.

import {FETCH_OBSERVATION} from '../actions/index';
import {DELETE_OBSERVATION} from '../actions/index';
const DEFAULT_STATE={all:[],count:null}
export default function(state=DEFAULT_STATE,action){
  switch (action.type) {
    case FETCH_OBSERVATION:
     return{
       all:state.all.concat(action.payload.data.model.observationInstanceList),
       count:action.payload.data.model.observationCount
     }
    case DELETE_OBSERVATION:
    return DEFAULT_STATE;
    default:
    return DEFAULT_STATE

  }
  return DEFAULT_STATE;
}

`