I have created a simple counter app that allows you to increment, decrement and reset the count. The next goal is to save the count, where you are able to show a history of previous calculations. Beginning with creating a function component for the 'Save Count' button.
I have gone about this by creating an empty useState array. Then creating an onClickFunction for saveCount, where the savedCount applies a spread operator to the count and then I map through the array every time the 'Save Count' button is pressed. This is based on a example of 'useState with Array' in the link below:
https://daveceddia.com/usestate-hook-examples/
You can find the code I have attempted below (also using this link: https://codesandbox.io/s/counter-app-project-save-nx7x6?file=/src/index.js:286-1297) :
function App() {
const [count, setCount] = useState(0);
const savedCount = useState([]);
const incrementCount = increment => {
setCount(count + increment);
};
const decrementCount = decrement => {
setCount(count - decrement);
};
const resetCount = () => {
setCount(0);
};
const saveCount = () => {
savedCount([
...count,
{
id: count.length
}
]);
resetCount();
};
return (
<div className="App">
<ButtonIncrement increment={1} onClickFunction={incrementCount} />
<ButtonIncrement increment={10} onClickFunction={incrementCount} />
<ButtonDecrement decrement={1} onClickFunction={decrementCount} />
<ButtonDecrement decrement={10} onClickFunction={decrementCount} />
<Reset onClickFunction={resetCount} />
<span>{count}</span>
<Save onClickFunction={saveCount} />
<ul>
{savedCount.map(count => (
<li key={count.id}>count</li>
))}
</ul>
</div>
);
}