Why this alert box is appearing twice in a simple useReducer Application,
Click here for the codesandbox link,
To regenerate the scenario
- increase the value of input using up arrow (Press only once)
- decrease the value of input by down key (Press only once)
here is the code
import "./styles.css";
import { useReducer } from "react";
const reducerFunction = (state, action) => {
switch (action.type) {
case "testing": {
if (action.payload.value > 0) {
return { ...state, testing: action.payload.value };
} else {
alert("some message");
return state;
}
}
default: {
throw new Error("Invalid Action");
}
}
};
export default function App() {
const defaultValue = {
testing: 0
};
const [state, dispatch] = useReducer(reducerFunction, defaultValue);
return (
<input
value={state.testing}
onChange={(e) => {
dispatch({ type: "testing", payload: { value: e.target.value } });
}}
type="number"
/>
);
}