Reputation: 912
I want to use this.forceUpdate()
in one of the handler named 'update' in withHandlers of my compose. I am using recompose to achieve the same. Find sample code below:
const abc = compose(
withHandlers(
update: () => () => this.forceUpdate()
)
)
But it is not working. Does anyone know how to use forceUpdate()
method of react in withHandlers of recompose library?
Is there any alternative to achieve same result as forceUpdate()
?
Upvotes: 1
Views: 1161
Reputation: 49
You can use withState
to make your own props.forceUpdate
, since all state updaters trigger the component to re-render.
IE:
withState('_forceUpdate', 'forceUpdate')
Then call props.forceUpdate()
wherever.
Upvotes: 1
Reputation: 131
There's forceUpdate in lifecycle.
We use it like this:
import { lifecycle } from 'recompose';
const listensForChangingModel = ( propName='model' ) => lifecycle( {
componentDidMount() {
this.onModelChanged = () => this.forceUpdate();
this.props[ propName ].on( 'change', this.onModelChanged );
},
componentWillUnmount() {
this.props[ propName ].off( 'change', this.onModelChanged );
},
componentDidUpdate( prevProps ) {
if ( prevProps[ propName ].cid !== this.props[ propName ].cid ) {
prevProps[ propName ].off( 'change', this.onModelChanged );
this.props[ propName ].on( 'change', this.onModelChanged );
}
},
} );
export default listensForChangingModel;
This make a higher-order component that forces update when the model fires change event.
Upvotes: 1
Reputation: 4464
You're using this
outside of your component's scope, so this
is undefined.
I don't know what do you want to achieve but you should try another way to do it.
Normally you should try to avoid all uses of forceUpdate()
Upvotes: 1