I'm having an issue in a simple React application; when I click a button, the onClick event is not fired properly on the first click. This has something to do with when the state is updated and when I call console.log(), but I'm not sure how to correct it. How do I get the onClick event in the code below to fire as it should on the first click?
This is a calculator app. When I click, say, the "9" button. The console prints, "". When I click "9" again, the console correctly prints "9," and will correctly print any other key I press thereafter.
import styled from 'styled-components';
import OutputScreen from './OutputScreen';
import FormulaScreen from './FormulaScreen';
import Keypad from './Keypad';
import { useState } from 'react';
export const CalcPadStyles = styled.div`
background-color: black;
width: 334px;
height: 420px;
display: flex;
flex-direction: column;
align-items: center;
font-size: 29px;
color: white;
position: absolute;
top: 50%;
left: 50%;
margin: -210px 0 0 -167px;
padding: 10px;
`;
const Calculator = () => {
const [pressedKey, setPressedKey] = useState('');
const [calcInput, setCalcInput] = useState(0);
function handleClick(e) {
e.preventDefault();
const outputValue = e.target.innerText;
setPressedKey(outputValue);
console.log(pressedKey);
}
return (
<CalcPadStyles>
<FormulaScreen />
<OutputScreen output={pressedKey} />
<Keypad clicked={e => handleClick(e)} />
</CalcPadStyles>
);
};
export default Calculator;