I'm trying to handle two form input values and save data to store with Redux Toolkit on submit. Seems simple but haven't really got the hang of it, yet.
My first thought was to keep the input values locally with useState and set data to store only when submitting the form. Just to prevent rendering on input change. But when submitting I'd like to save it to store.
export default function App() {
const [user, setUser] = useState({
length: null,
width: null
});
const dispatch = useDispatch();
const handleChange = (e) => {
const { name, value } = e.target;
setUser({ ...user, [name]: value });
};
const handleSubmit = (e) => {
e.preventDefault();
// set data to store on submit
dispatch(setUser);
console.log(setUser);
};
return (
<div className="App">
<form onSubmit={handleSubmit}>
<input
type="text"
name="length"
onChange={handleChange}
placeholder="Add Length"
/>
<input
type="text"
name="width"
onChange={handleChange}
placeholder="Add Width"
/>
<button type="submit">Submit</button>
</form>
<User />
</div>
And here's my slice function:
import { createSlice } from "@reduxjs/toolkit";
export const userSlice = createSlice({
name: "user",
initialState: {
length: null,
width: null
},
reducers: {
setUser: (state, action) => {
state.user.length = action.payload;
state.user.width = action.payload;
}
}
});
export const { user, setUser } = userSlice.actions;
export const selectUser = (state) => state.user;
export default userSlice.reducer;
I've managed it to work with one input but not when there's multiple inputs. See codesandbox for full example.
Thanks in advance!
CodePudding user response:
Here you are dispatching the setUser action with an empty value
const handleSubmit = (e) => {
e.preventDefault();
// set data to store on submit
dispatch(setUser);
console.log(setUser);
};
Change it to this.
const handleSubmit = (e) => {
e.preventDefault();
// set data to store on submit
dispatch(setUser(user));
console.log(setUser);
};
And in userSlice.js change it to this.
reducers: {
setUser: (state, action) => {
state.length = action.payload?.length;
state.width = action.payload?.width;
}
}