I need help with this react-redux code. There is an input field which accept numbers and adds them to the counter above. I want to restart the counter to 0 if the input is not a number, however when I type any char different from int it set the counter to NaN. I tried to cast the value of the state from the reducer and from a separate function but neither worked.
//counterSlice.js
import { createSlice } from "@reduxjs/toolkit";
export const counterSlice = createSlice({
name: "counter",
initialState: {
value: 0,
},
reducers: {
increment: (state) => {
// Redux Toolkit allows us to write "mutating" logic in reducers. It
// doesn't actually mutate the state because it uses the Immer library,
// which detects changes to a "draft state" and produces a brand new
// immutable state based off those changes
state.value = 1;
},
decrement: (state) => {
state.value -= 1;
},
incrementByAmount: (state, action) => {
state.value = action.payload;
},
reset: (state) => {
state.value = 0;
},
},
});
// Action creators are generated for each case reducer function
export const { increment, decrement, incrementByAmount, reset } =
counterSlice.actions;
export default counterSlice.reducer;
//Counter.js
import React, { useState } from "react";
import { useSelector, useDispatch } from "react-redux";
import { decrement, increment, incrementByAmount, reset } from "./counterSlice";
export function Counter() {
const count = useSelector((state) => state.counter.value);
const dispatch = useDispatch();
const [add, setAdd] = useState();
const changeAdd = (e) => {
e.preventDefault();
if (isNaN(add)) {
dispatch(reset());
}
dispatch(incrementByAmount(Number(add)));
setAdd("");
};
return (
<div>
<div>
<button
aria-label="Increment value"
onClick={() => dispatch(increment())}
>
Increment
</button>
<span>{count}</span>
<button
aria-label="Decrement value"
onClick={() => dispatch(decrement())}
>
Decrement
</button>
<form onSubmit={changeAdd}>
<input
type="text"
value={add}
onChange={(e) => setAdd(e.target.value)}
/>
<button type="submit">send</button>
</form>
</div>
</div>
);
}
export default Counter;
CodePudding user response:
You should add a return
at the end of the if (isNaN(add))
, otherwise you're still dispatching incrementByValue
with the value that isn't a number.
CodePudding user response:
You should convert value to number before checking if it's NaN:
if (isNaN(Number(add))) {