javascriptreactjsreact-hooksuse-statemathjs

making React work together with math.js library


for some reason my React component seems not to be working with the math.js library. Whenever I try to get the output of the following code on the console (without resetting the state it seems to be working fine and correct value gets outputted in the console), but if I try to apply the result of the evaluate() function in React component with applying it in the setTotal() nothing happens.

Could you please let me know what am I doing wrong in here and why it is not working?

Here is my pen

function App() {
  const expression = "3+5*6-2/4"
  const { total, setTotal } = React.useState("0")
  
  function handleCalc() {
    const total = math.compile(expression)
    const result = total.evaluate()
    setTotal(result)
  }
  
  return (
    <div>
      <h1>Calculator</h1>
      <p>{`Expression: ${expression}`}</p>
      <button onClick={handleCalc}>Calculate</button>
      <h1>{total}</h1>
    </div>
  )
}

ReactDOM.render(<App />, document.getElementById("root"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.3.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.3.0/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjs/7.0.1/math.min.js"></script>

<body>
  <div id="root"></div>
</body>


Solution

  • You should destruct useState as an array.

    const [total, setTotal] = React.useState("0")
    

    const { useState } = React;
    
    function App() {
      const expression = "3+5*6-2/4"
      const [total, setTotal] = useState("0")
      
      const handleCalc = () => {
        const total = math.compile(expression)
        const result = total.evaluate()
        setTotal(result)
      }
      
      return <div>
          <h1>Calculator</h1>
          <p>Expression {expression}</p>
          <button onClick={handleCalc}>Calculate</button>
          <h1>{total}</h1>
        </div>
    }
    
    ReactDOM.render(<App />, document.getElementById("root"))
        <script src="https://unpkg.com/react/umd/react.development.js"></script>
        <script src="https://unpkg.com/react-dom/umd/react-dom.development.js"></script>
        <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/mathjs/7.0.1/math.min.js"></script>
    
    <body>
      <div id="root"></div>
    </body>