Hello all,
maybe one of you can help me with a problem.
Analogous to Mosh’s Redux course, I have implemented an api middleware with Axios in my project.
In my component I load a user via dispatch and want to update it later with a form submit.
I want to use a local state to not have to dispatch every onChange event. Only with the submit I want to update my global state.
Currently I am stuck on how to call the local setState (setUser) within my useEffect function with the user loaded.
import { useDispatch, useSelector } from "react-redux";
import { useEffect, useState } from "react";
import { loadUser, saveUser } from "../store/users";
const Debug = () => {
const userId = 5;
const dispatch = useDispatch();
const [user, setUser] = useState({});
useEffect(() => {
dispatch(loadUser(userId));
//HOW TO call setUser with the loaded User from the dispatch Action ?
//setUser(????)
}, [dispatch]);
const handleChange = (e) => {
setUser({
...user,
[e.target.id]: e.target.value,
});
};
const handleSubmit = (e) => {
e.preventDefault();
dispatch(saveUser(user));
};
return (
<div>
<form onSubmit={handleSubmit}>
<input
id="firstName"
value={user.firstName || ""}
onChange={handleChange}
/>
<button type="submit">Submit</button>
</form>
</div>
);
};
export default Debug;
My action creators looks like
// Action Creators
const url = "/users";
export const loadUser = (userId: number) => (dispatch: any, getState: any) => {
return dispatch(
apiCallBegan({
url: url + "/" + userId,
onSuccess: userReceived.type,
})
);
};
export const saveUser = (user: IUser) => (dispatch: any, getState: any) => {
return dispatch(
apiCallBegan({
url: user.userId > 0 ? url + "/" + user.userId : url,
method: user.userId > 0 ? "put" : "post",
data: user,
onSuccess: userAdded.type,
})
);
};