Aimadev
Aimadev

Reputation: 3

Refactoring to make a function reusable with setState

I need to make this function reusable but I don't understand how setState will be passed to be available in it

function getRandomEmployee(updateStateFn){
      const filteredEmployee = employeeList.filter(image => image.hasImage === true)
      const random = filteredEmployee[Math.floor(Math.random() * filteredEmployee.length)]
      const randomOpt1 = filteredEmployee[Math.floor(Math.random() * filteredEmployee.length)]
      const randomOpt2 = filteredEmployee[Math.floor(Math.random() * filteredEmployee.length)]
      const randomOpt3 = filteredEmployee[Math.floor(Math.random() * filteredEmployee.length)]
      const randomOptions = [random.fullName, randomOpt1.fullName, randomOpt2.fullName, randomOpt3.fullName]
      randomOptions.sort(() => { return 0.5 - Math.random() })
    setState(state => {
      const newState = updateStateFn && updateStateFn(state)
      return {...newState, randomEmployee: random, randomOptions: randomOptions, playerIsWin:'', disableFieldset: false}
    })
  }

I expect the function to output random 4 names and return new states on setState

Upvotes: 0

Views: 200

Answers (2)

ehutchllew
ehutchllew

Reputation: 958

I've noticed a few things here:

1) You have some repetitive code -> filteredEmployee[Math.floor(Math.random() * filteredEmployee.length)] It would be a good idea to abstract it out. You could do this like:

function getRandomIndex(dataArray) => dataArray[Math.floor(Math.random() * dataArray.length)]

Then you could just call the function like: const randomOption = this.getRandomIndex(filteredEmployee)

2) For your setState to work, it depends on where this method of yours is located. Is it inside of the component that is handling the state? If it's not, one option is to have your getRandomEmployee simply return the object you need and have the component invoking it setState instead.

Upvotes: 0

thedude
thedude

Reputation: 9812

I would make this function pure and use it when you need to generate these random names, e.g.

class SomeComponent extends Component {
    handleClick = () => {
        const {random, randomOptions} = getRandomEmployee()
        this.setState({
           randomOptions,
           random,
        })
    }
}

Upvotes: 1

Related Questions