I have a function which acts as a sort of focal point before calling my api.
I want to reduce the bloat a little by simplifying my if statements.
Currently I have a list of statements. 2 of which are shown below
    if (this.props.source === 1) {
      api.updateData01(id, data).then(res => {
        this.hideModal()
        this.props.updateData01()
        console.log('DATA UPDATED')
      })
    }
    if (this.props.source === 2) {
      api.updateData02(id, data).then(res => {
        this.hideModal()
        this.props.updateData02()
        console.log('DATA UPDATED')
      })
    }
I'd like to simplify it by bringing my if statements up and instead dynamically rename the functions.
Something along the lines of
    if(this.props.source === 1){
      //rename updateData to updateData01
    }
    if(this.props.source === 2){
      //rename updateData to updateData02
    }
    api.updateData01(id, data).then(res => {
      this.hideModal()
      this.props.updateData01()
      console.log('DATA UPDATED')
    })
I've never had to rename a function before so am unsure how to begin.
I've attempted something like this but it obviously wasn't going to work.
   if(this.props.source === 1){
      const dataSource = 01
    }
   api.updateData + datasource + (.....
                Instead of renaming your functions you could use dynamic property names to access the correct function based on a hash (api)
const api = {
    updateData01 : () =>{},
    updateData02 : () =>{},
    /*...*/
    updateData0N : () =>{}
}
api[`updateData0${this.props.source}`]().then(/*...*/)
                        @Dupocas approach is probably the one I'd go with. That said, it's also possible to accomplish this with an array:
// your updateData prop would look something like this:
// this.props.arrFn = [() => console.log('1'), () => console.log('2')]
const fireByDataSource = (source) => this.props.arrFn[source - 1](id, data)
componentDidMount() {
    if(this.props.source) return fireByDataSource(this.props.source)
    api.updateData01(id, data).then(res => {
      this.hideModal()
      fireByDataSource(1)
      console.log('DATA UPDATED')
    })
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With