I’m displaying objects from the array. example :
export default function App() {
const data = [
{ id: 1, more: "string 1" },
{ id: 2, more: "string 2" },
{ id: 3, more: "string 3" }
];
// here if index becomes 4 it breaks as there is no object in the data with index 4
const [index, setIndex] = React.useState(0);
const submitHandler = () => {
// probably there we need any type of if statement but I don't; know how to compare with index
setIndex(index + 1);
};
const showDat = (data, index) => {
return <p>{data[index].more}</p>;
};
return (
<div className="App">
<Container>
<Col md={8}>
<Card style={{ minHeight: "40rem" }}>
{showDat(data, index)}
<Card.Footer>
<Button
variant="outline-danger"
onClick={submitHandler}
className="mx-1"
>
{" "}
Skip
</Button>
<Button variant="primary" onClick={submitHandler}>
{" "}
Continue
</Button>
</Card.Footer>
</Card>
</Col>
</Container>
</div>
);
}
The problem is if index is not available in the array then code breaks and I want to add error handling, like if index is not equal then make the continue button disable or something like that.
So how can I compare the count of index of the array to index state ?
Running Example in CodeSandBox