DaOneRom
DaOneRom

Reputation: 294

Rewrite shorter version function

I have a function that calls out particular states but with a semi-identical lines. Here's my function;

DoThis(type) {
   if (type === 'a') {
      this.setState({ activeA: { display: 'block', opacity: 1 } }, () => setTimeout(() => {
         this.setState({ activeA: { opacity: 0 } }, () => setTimeout(() => {
            this.setState({ activeA: { display: 'none' } })
         }, 300))
      }, 2000));
   } else if (type === 'b') {
      this.setState({ activeB: { display: 'block', opacity: 1 } }, () => setTimeout(() => {
         this.setState({ activeB: { opacity: 0 } }, () => setTimeout(() => {
            this.setState({ activeB: { display: 'none' } })
         }, 300))
      }, 2000));
   } // ...some other active(n) conditions.
}

It's pretty messy and I just want it to be free from congestion.

This is my state:

this.state ={
   activeA: { display: 'none', opacity: 0 },
   activeB: { display: 'none', opacity: 0 },
   // ...some other active(n) states...
}

Any way of resolving this kind of issue?

Upvotes: 0

Views: 82

Answers (2)

georg
georg

Reputation: 214949

To escape the callback hell, you can add a simple function like this:

const delay = (time = 0) => new Promise(r => setTimeout(r, time));

And then rewrite that in the linear fashion:

async DoThis(type) {
    let key = 'active' + type.toUpperCase();

    this.setState({[key]: {display: 'block', opacity: 1}})
    await delay(300);
    this.setState({[key]: {opacity: 0}});
    await delay(2000);
    this.setState({[key]: {display: 'none'}});
}

Upvotes: 1

jered
jered

Reputation: 11571

Use a combination of template string and computed property name:

DoThis(type) {
  const fieldName = `active${type.toUpperCase()}`;
  this.setState({[fieldName]: { display: 'block', opacity: 1 } }, () => setTimeout(() => {
     this.setState({ [fieldName]: { opacity: 0 } }, () => setTimeout(() => {
        this.setState({ fieldName]: { display: 'none' } })
     }, 300))
  }, 2000));
}

Template strings let you easily construct a string with complex JavaScript values:

  const myString = "some text";
  const myTemplateString = `you can insert ${myString} into a template string`;
  // myTemplateString = "you can insert some text into a template string"

Computed property values let you assign values to the fields of an object without knowing ahead of time (i.e. "hard coding") what the fields are:

  const myFieldName = "pizza";
  const myObject = {
    [myFieldName]: "delicious"
  };
  // myObject = {pizza: "delicious"}

Upvotes: 0

Related Questions