Search code examples
javascriptreactjsfunctionglobal-variables

Accessing a value of a gotten from a function from outside the function


I have the piece of code below and I am having an issue accessing the BMI outside the function as it returns undefined. The function itself should return the solution of the BMI when the 'calculate' button is clicked. i need to access the BMI value from outside the function scope but it keeps returning undefined. Its already defined outside the function so I'm not sure why it's acting up. i actually found a workaround to the issue but the resulting code wasn't looking as optimised.

const { weight, height } = userInput;

    /**Calculate the BMI and round to two decimal places */
    let BMI;
    const calculateBMI = () => {
        BMI = weight / (height * height);
        console.log(BMI); //logs the value of BMI onClick of the button
        return BMI;
        //let BMIValue = Math.round(BMI * 100) / 100;
        //return BMIValue;
    };

    console.log(BMI); //logs undefined regardless

    return (
        <div>
            <div>
                <label htmlFor="height">Height:</label>
                <input
                    type="number"
                    name="height"
                    onChange={handleChange}
                    value={userInput.height}
                />
            </div>
            <div>
                <label htmlFor="weight">Weight:</label>
                <input
                    type="number"
                    name="weight"
                    onChange={handleChange}
                    value={userInput.weight}
                />
            </div>
            <button onClick={calculateBMI}>
                Calculate
            </button>
        </div>
    );

Solution

  • If you want to sync data from your UI after a user interaction then you should go with useState (that's actually an strong use case for it).

    So you should try

    
    const [BMI, setBMI] = useState();
    
    const calculateBMI = () => {
           currentBMI = weight / (height * height);
           setBMI(currentBMI);
    };
    
    console.log(BMI)