Caner
Caner

Reputation: 59198

Dynamically create callbacks

I have 10s of callback methods, they are all in the form of:

xCallback = (value) => {
    this.setState({x: value}, () => {
        this.update();
    });
};

yCallback = (value) => {
    this.setState({y: value}, () => {
        this.update();
    });
};
...

I pass these methods to child components as callbacks(3rd party components that I cannot modify):

<ChildComponent ... callback={this.xCallback}/>

Is there a way to shorten this code and get rid of duplicate code?

Upvotes: 0

Views: 175

Answers (2)

Dupocas
Dupocas

Reputation: 21317

You could accept an aditional parameter which is the key to be updated. Since you can't change the signature of the function passed to your child component you can use currying to return a dynamic callback with a fixed signature

const generateCb = key => value => this.setState({ [key] : value }, () => {})

return <Child callback={generateCb('x')}

Where generateCb('x') will evaluate to

value => this.setState({ 'x' : value }, () =>{})

Upvotes: 2

Oleksandr Paiziak
Oleksandr Paiziak

Reputation: 382

You can set second parameter as key

cCallback = (value, key) => {
    this.setState({[key]: value}, () => {
        this.update();
    });
};

Upvotes: 1

Related Questions