DEV Community

Discussion on: React's new Context API and Actions

Collapse
 
cyril36 profile image
cyril36

Hi,
I am using the way you are explaining in this post but i am facing an issue.

my provider state looks like :
export class CalendarProvider extends React.Component {
state = {
content: '',
dispatch: action => {
this.setState (state => CalendarReducer (state, action));
},
};

with the CalendarReducer doing :
const CalendarReducer = (state, action) => {
switch (action.type) {
case 'CONTENT': {
return Object.assign (state, {content: action.payload});
}
}
};

I would like to clone the Provider state object in my component state :
class Calendar extends Component{
//my component state = clone of the provider state
this.state = Object.assign ({}, this.props.store);
}

Now I have 2 differents object :

  • this.state (calendar State)
  • this.props.store (Calendar Provider State)

I can modify both of them doing :

  • this.state = object.assign(this.state,{content:'test'})
  • this.props.store = object.assign(this.props.store,{content:'retest'}) result : this.state ={ content:'test' } this.props.store ={ content:'retest' }

both value are changed independently.

BUT, when I am trying to do the same thing with the dispatch function, it only change the state of the provider :

this.state.dispatch({type:'CONTENT',payload:'dev'})
The result is :
this.state ={
content:'test'
}
this.props.store ={
content:'dev'
}

instead of :
this.state ={
content:'dev'
}
this.props.store ={
content:'retest'
}

The dispatch function only update the provider component.
the this.state.dispatch point to this.props.store.dispatch.

How can i do to have 2 different function :
this.state.dispatch that update this.state (the consumer)
and
this.props.store.dispatch that update this.props.store (the provider)

I hope it is clear enough
And hopefully you know where is my mistake

Thank you