2

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

2
  • 1
    Without knowing how your component uses that it is hard to give a definitive answer. Also where does prodStatus come from? Maybe it could be refactored to use useReducer or maybe a simple function could be sufficient. But at least 10 times in a single component already seems suspicious to me. Also what is the semantic difference of isSold = true and isStillThere = false? Commented Sep 12, 2019 at 14:21
  • 1
    Custom hooks may help. Here there is a useBoolean hook. daveceddia.com/custom-hooks Commented Sep 12, 2019 at 14:23

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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>;
}

Comments

-1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.