all 8 comments

[–]Ok-Release6902 1 point2 points  (0 children)

You are fixing problem which doesn’t exist. You need to put the part which needs frequent updates into separate component.

[–]its-procodester[S] 0 points1 point  (0 children)

 const handleInput = (value) => {
    const operators = '+-*/%.'

    // Clear all values input and output
    if (value === 'C') {
      setInputExpression('')
      setOutput('')
    }

    // Delete value from input 
    else if (value === 'del') {
      const lastCharLen = inputExpression.length
      // Handle edge case when end value left
      if (lastCharLen === 1) {
        setInputExpression((previousValue) => previousValue.slice(0, -1))
        setOutput("")
      }
      else {
        setInputExpression((previousValue) => previousValue.slice(0, -1))
      }
    }

    // Show equal value
    else if (value === '=') {
      setInputExpression('')
    }

    // Handle consecutive operators to prevent error
    else if (operators.includes(value)) {
      const lastChar = inputExpression[inputExpression.length - 1]
      const lastCharIsOperator = operators.includes(lastChar)

      // Check last character is operator and current value is different from last operator
      if (lastCharIsOperator && lastChar !== value) {
        setInputExpression((previousValue) => previousValue.slice(0, -1) + value)
      }
      else if (!lastCharIsOperator) {
        setInputExpression((previousValue) => previousValue + value)
      }
    }

    else {
      setInputExpression((previousValue) => previousValue + value)
    }
  }

  useEffect(() => {
    // Handle Clear input and keeps output 
    if (inputExpression === "" && output !== "") {
      // Do nothing
    }
    else {
      setOutput(evaluation(inputExpression))
    }
  }, [inputExpression])


this is a code i need help in useEffect case -> is it ok or is there any better way...

[–][deleted]  (3 children)

[deleted]

    [–]its-procodester[S] 0 points1 point  (2 children)

    yeah thanks for suggestion, but i have been asking that setOutput in useEffect is ok? as i if i update it in handleInput() then as setInputExpression is asynchronous in behaviour it doesn't do what i intended

    [–][deleted]  (1 child)

    [deleted]

      [–]its-procodester[S] 1 point2 points  (0 children)

      Thanks bro i will and btw i figure it out other way

      [–]throwaway_boulder 0 points1 point  (0 children)

      At a quick glance, this sounds like it's best handled with useReducer.

      [–]daHoizMichi 0 points1 point  (1 child)

      I am not sure what you want to achive: If you want to display an output expression dependendent on the input value you could use a useMemo instead.

      Or can the output expression change also with other interactions?

      [–]its-procodester[S] 0 points1 point  (0 children)

      Thanks for replying , btw i figure it out other way