Currently using getDerivedStateFromProps for the first time. My code works and it does what I want it to do, but I am getting a warning in my console that is confusing to me since my code is working. Warning : "getDerivedStateFromProps(): A valid state object (or null) must be returned. You have returned undefined." Is there a better way of writing the getDerivedStateFromProps in order to get rid of the warning in the console?
static getDerivedStateFromProps(props, state) {
state.currentUser.id =
props.location.state && props.location.state.user
? props.location.state.user.id
: state.currentUser.id;
state.currentUser.name =
props.location.state && props.location.state.user
? props.location.state.user.name
: state.currentUser.name;
state.currentUser.roles =
props.location.state && props.location.state.user
? props.location.state.user.roles
: state.currentUser.roles;
state.currentUser.hasAuthenticated = true;
}
The
getDerivedStateFromPropsmethod should return the updated slice of state, instead of updating the state object passed as an argument.I've added
...state.currentUserin case there are some other fields ofstate.currentUserthat you want to preserve into the new state.