Hi everyone, I am really confused. I have managed to update my array in my state but cant clear a string from a ‘0’ to ‘’ (empty string) using setState. can someone else. I am using setDisp to try and clear the 0 when a user enters a number. Thanks. I feel like I am not using react hooks correctly but updating an array has worked.Help!
const clearDisplay = () => {
setSums([]);
setDisp('0');
setTotal('');
};
function numberClicked(e) {
console.log(e.target.textContent);
// This clears the 0 when a user types a number
if (currDisp === '0') {
setDisp('');
}
It’d be easier with more code… do you have it in a sandbox or something we can look at?
I think I can code what you’re trying to accomplish but you seem to be using a different method of using hooks than I know. I use useState and I’ve only declared it in the function component in which it would be used.
Hi here is my github code, I was using functions within the main react component function, if there is a better way fo doing it I am happy to hear about it https://github.com/Webdev-DavidM/React-hooks-calculator
I had a play with your app and I can’t see a way in the UI to click a button that ends up with a 0 being displayed (and not 00 etc.) unless you press AC. But when your press AC the code gets run, but then some code is called later which will call setDisp again.
What I suggest for problems like this is to get used to using the debugger. You can quickly see what is going on. Because you are using create-react-app it generates “source maps” which basically means you can easily debug the application in Chrome or Firefox, using F12. Open the calculation.js and put a breakpoint on the blankDisplay
function (as you have called it in the Github repo) and then you can see what happens next by stepping through.
Hi Martin, thanks for the response, when it throws an error but shows nothing in the console, the error reads
error("State updates from the useState() and useReducer() Hooks don't support the " + 'second callback argument. To execute a side effect after ' + 'rendering, declare it in the component body with useEffect().');
I tried but I can’t reproduce that having cloned the github code link you provided. And the code you posted looks a bit different.