Sreeram Venkitesh
Sreeram Venkitesh

Reputation: 318

Default value for React state storing integer values

I have a selectedId React state that stores integer values. The state is updated with an id integer, when an item is selected from a list. Once selectedId is set, the user can click a delete button to delete the selected element, after which selectedId should be set back to its initial value again.

What is the recommended default value for selectedId? Should it set to null ( useState(null) and setSelectedId(null) ), or be undefined ( setSelectedId() )

const [selectedId, setSelectedId] = useState();
const handleSelect = id => {
  setIsAlertOpen(true);
  setSelectedId(id);
};
<Button onClick={() => {
  deleteItem(selectedId)
  setSelectedId();
}/>

Upvotes: 1

Views: 1817

Answers (1)

Nishanth
Nishanth

Reputation: 354

Create a constant to store the initial value, and when you delete the selectedId restore it your initial value.

const initialValue = null;
const [selectedId, setSelectedId] = useState(initialValue);

const handleSelect = id => {
  setIsAlertOpen(true);
  setSelectedId(id);
};

<Button onClick={() => {
  deleteItem(selectedId)
  setSelectedId(initialValue);
}/>

Upvotes: 2

Related Questions