Search code examples
javascriptreactjsbuttonconditional-statementscreate-react-app

How to toggle two different buttons (function/text) based on external condition (e.g. num of items purchase)


I am revisiting an earlier idea to toggle between two buttons conditionally in a CRA.

import ...
const ...

export const Index = () => {

  // Boolean to toggle buttons conditionally
  const [reachMax] = React.useState( id <= 8 );

  return (

  <div>{(reachMax &&
    <div{(reachMax &&
      <button 
        id="btn1"
        type="button"
        className="..." 
        onClick={event}
      >
        Event A: "Sales!"
      </button>
    </div>)
  ||
    <div>
      <button
        id="btn2"
        type="button"
        className=" "
        disabled='true'
      >
        Event B: "Out of Stock"
      </button>
    </div>)
    }
  )
}

Using a state hook. The condition for the Boolean ( contract.tokenUri.id <= 8 ) is taken from an external smart contract dynamically. How can the condition be set so that it would not return an undefined error?


Solution

  • Managed to resolve by setting this condition in order to read the ID off the smart contract:

    const reachMax = mintedState.state === "SUCCESS" && mintedState.data.length <= 8;

    There's no need for the constructor as the state is directly passed into the app from the external contract. Once the nmintedState.state condition is satisfied (success), the data.length (a proxy for the ID) can be used as the final condition for setting the right button.

    This problem is specific to the combination of Solidity contract and ReactJS used.