Roxy'Pro
Roxy'Pro

Reputation: 4454

Avoid code repetition - reactJs - javascript

All the time in my app I'm repeating code like this:

if (prodStatus !== Product.Sold) {
  this.setState({isSold: false});
} else {
  this.setState({isStillThere: false});
}

I've repeated it in my component at least 10x, could I somehow refactor it to looks more nicer or something like that?

Thanks guys

Cheers

Upvotes: 2

Views: 556

Answers (3)

Maria
Maria

Reputation: 295

Alternately, you could just use this.setState({isSold: prodStatus === Product.Sold})

And then instead of checking this.state.isStillThere in your code, just check !this.state.isSold.

Upvotes: 2

dodgez
dodgez

Reputation: 551

Here in the React Tutorial, they showcase an example situation similar to what you are dealing with, namely, state that needs to be visible for sub-components but shouldn't be repeated.

They pass the desired property into the props of the sub-component, which is what is generally done (in my experience) with properties that need to be passed down.

Here is some example code:

import React from 'react';
import SubComponent from 'SubComponent';

// MainComponent has prodStatus in props or state.
export default class MainComponent extends React.Component {
  render() {
    return <div><SubComponent prodStatus={this.state.prodStatus} /></div>;
  }
}

Or if you prefer the function syntax (I am not familiar so please let me know if I made a mistake):

import React, { useState } from 'react';
import SubComponent from 'SubComponent';

// MainComponent has prodStatus in props or state.
export default function MainComponent(props) {
  const [prodStatus, setProdStatus] = useState(/*prodStatus code*/);
  return <div><SubComponent prodStatus={prodStatus} /></div>;
}

Upvotes: 0

Popescu David Ioan
Popescu David Ioan

Reputation: 106

You could use ternary operator

    prodStatus !== Product.Sold ?
 this.setState({ isSold: false }) :
 this.setState({ isStillThere: false })

Further refference:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator

Upvotes: -1

Related Questions