Skip to content

Instantly share code, notes, and snippets.

@ifindev
Created May 4, 2021 00:02
Show Gist options
  • Save ifindev/8900c1cc014456cf6d93fd8fd82281da to your computer and use it in GitHub Desktop.
Save ifindev/8900c1cc014456cf6d93fd8fd82281da to your computer and use it in GitHub Desktop.
Set State Array
import { useState } from 'react';
function App() {
const [counters, setCounters] = useState([
{ id: 1, value: 0 },
{ id: 2, value: 0 },
{ id: 3, value: 0 },
{ id: 4, value: 0 },
]);
const [count, setCount] = useState(0);
const handleIncrement = (counter, counters) => {
const index = counters.indexOf(counter);
counters[index].value++;
setCounters(counters);
};
const handleDecrement = (counter, counters) => {
const index = counters.indexOf(counter);
counters[index].value--;
setCounters(counters);
};
const increment = (count) => {
count = count + 1;
setCount(count);
};
return (
<div className="container mt-5">
<div>
<p>You clicked {count} times</p>
<button onClick={() => increment(count)}>Click Me</button>
</div>
<div>
{counters.map((counter) => {
return (
<div
className="d-flex flex-row align-items-center mt-2"
key={counter.id}
>
<span
style={{ fontSize: 24 }}
className="badge m-2 badge-primary"
>
{counter.value}
</span>
<button
style={{ height: 38 }}
className="btn btn-secondary mr-2"
onClick={() => handleIncrement(counter, counters)}
>
<strong>+</strong>
</button>
<button
style={{ height: 38 }}
className="btn btn-warning mr-2"
onClick={() => handleDecrement(counter, counters)}
>
<strong>-</strong>
</button>
</div>
);
})}
</div>
</div>
);
}
export default App;
@mwafa
Copy link

mwafa commented May 4, 2021

Sepertinya gini jadi lebih ringkas

const handleIncrement = (counter) => {
    setCounters((counters) => counters.map(c => {
        if (c.id === counter.id) c.value++
        return c
    }))
};

yang ini juga

const increment = () => {
    setCount(count => count + 1);
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment