EN VI

Javascript - Value of variable gets lost outside a try-catch statement in a react component?

2024-03-11 09:00:05
How to Javascript - Value of variable gets lost outside a try-catch statement in a react component

So I'm trying to display some math for a school project using react and MathJax and MathJs, the code is the following:

const InputForm = () => {

    let latex;
    let node;
    let inicial;
//    MathJax.typesetClear();

    let parenthesis = 'keep'
    let implicit = 'hide'
    
    //'sqrt(75 / 3) + det([[-1, 2], [3, 1]]) - sin(pi / 4)^2'
    
    const [inputExpressionText, setInputExpressionText, ] = useState(initial);
    
    function initial(){
      node = math.parse('sqrt(75 / 3) + det([[-1, 2], [3, 1]]) - sin(pi / 4)^2')
      latex = node ? node.toTex({parenthesis: parenthesis, implicit: implicit}) : ''
      console.log('Node en estado inicial:', node)
      console.log('LaTeX en estado inicial:', latex)
      
      return 'sqrt(75 / 3) + det([[-1, 2], [3, 1]]) - sin(pi / 4)^2';
    }

    useEffect(() => {
      //OnInput();
    },[inputExpressionText,])

    
  
  
  

    

const OnInput = function () {
  
  console.log(inputExpressionText);
  inicial = document.getElementById("input")
  node = null;

  try {
    console.log("antes de node initial", inicial.value);
    console.log("antes de node", node);
    node = math.parse(inicial.value)
    console.log("después de node", node);
    
  }
  catch (err) {
    console.log("No entro a node = math",   )
    console.log(err.toString())
  }

  try {
    // export the expression to LaTeX
    latex = node ? node.toTex({parenthesis: parenthesis, implicit: implicit}) : ''
    console.log('LaTeX expression dentro de funcion:', latex)

    // display and re-render the expression
    
  }
  catch (err) {
  }
  console.log("lates en fuera del try-catch",latex)
}
  console.log("lates xfinal",latex)
  console.log("inputExpressionText ", inputExpressionText)
    return (
        <table className=' table  justify-content-between  '>
          <tbody>
              <tr>
                  <th>Expression</th>
                  <td><input type="text"  onInput={(e) =>{
                          setInputExpressionText(e.target.value);
                          OnInput()
                        }} id="input" value={inputExpressionText}/></td>
              </tr>
              <tr>
                  <th>Pretty print</th>
                  <td><PrettyInput latex={latex}/></td>
              </tr>
              <tr>
                  <th>Result</th>
                  <td><Result input={node} /></td>
              </tr>
          </tbody>
        </table>
    )
}

export default InputForm

the problem is in this part

try {
    // export the expression to LaTeX
    latex = node ? node.toTex({parenthesis: parenthesis, implicit: implicit}) : ''
    console.log('LaTeX expression inside function:', latex)

    // display and re-render the expression
    
  }
  catch (err) {
  }
  console.log("lates en fuera del try-catch",latex)
}
  console.log("lates xfinal",latex)

When latex variale gets the tex inside the function, the console.log('LaTeX expression inside function:', latex) confirms it, console shows the corresponding tex value.

But called again right outside the OnInput function, it shows undefined breaking the code.

I've tried to used the proposed example mathJs in here adapting it to a react component.

That approached worked only if added live while working with vite, but stopped working if reloaded as it says the dom it's not loaded.

I'm really stuck

Solution:

Explanation

This is because the const only has context within the try block. If you want this to be accessible outside the block you need to declare it before the block and set it accordingly.

Solution

There are two main ways to do this, either with state or let.

Here's an example with useState:

//make sure to import {useState} from 'react' to use this
//declaring the variable outside of the block will allow it to be used anywhere
[latex, setLatex] = useState('')

try {
    // export the expression to LaTeX
    setLatex(node ? node.toTex({parenthesis: parenthesis, implicit: implicit}) : '')
    console.log('LaTeX expression inside function:', latex)

    // display and re-render the expression
    
  }
  catch (err) {
  }
  console.log("lates en fuera del try-catch",latex)
}
  console.log("lates xfinal",latex)

Here is an example with let (this will not persist like state though, it will be dumped on every re-render)

let latex = ''

try {
    // export the expression to LaTeX
    latex = node ? node.toTex({parenthesis: parenthesis, implicit: implicit}) : ''
    console.log('LaTeX expression inside function:', latex)

    // display and re-render the expression
    
  }
  catch (err) {
  }
  console.log("lates en fuera del try-catch",latex)
}
  console.log("lates xfinal",latex)


Note to author: Welcome to stackoverflow!

When you get answers to questions you can refer to this link from stackoverflow https://stackoverflow.com/help/someone-answers to see how to respond to answers correctly!

For example if you liked this you can upvote and if this solved your question make sure to mark it as answered so others know!

:-) happy coding and hope this helps!

Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login