B4BIPIN
B4BIPIN

Reputation: 353

Can I bind store's state with a component in react-redux?

I am Newbie in react-redux, I created a small CRUD application with react-redux, when I click over add button from a child component it takes data from all input boxes and updates my store's array with the help of Reducer.

const initialState = {
itemObjectArr:[] }

My Reducer updates this itemObjectArr, and send it to needy component with the help of connect(mapStateToProps)(NeedyChildComponent) function. Now the real problem occurs when I try to print state.itemObjectArr on the console.

const  mapStateToProps = (state)=>{
console.log(state.itemObjectArr);
return  {itemObject:state.itemObjectArrs}}

Above code gives an error on console TypeError: Cannot read property 'itemObjectArrs' of undefined and if I do console.log(state) it prints objects contained array easily without any error.

I searched for this error but not get anything important, I think this store's state is immutable and when it passes to mapStateToProps function as an argument then mapStateToProps checks changes in state and if it does not get any changes then it returns an error. maybe this is occurring here.

Upvotes: 0

Views: 483

Answers (1)

ToneCrate
ToneCrate

Reputation: 544

What does your reducer look like? Since the store is returned as undefined in your component, it sounds to me that you haven't defined a default case in your switch statement that returns the initial state before your update action is executed, like:

const myReducer = (state, action) => {
  switch (action.type) {
    case 'UPDATE_ITEM_OBJECT_ARR': return { itemObjectArr: [ 1, 2, 3] }

    default:
      return initialState;
  }
}

Upvotes: 1

Related Questions