Reactjs Redux updating data values from the state/store with an input

Viewed 755

I have a state that has multiple users initial State of the reducer

const initialState = [
  {
    id: 1,
   name:"thename",
   lastName: "Lastname"
  },
  {
    id: 2,
   name:"thename",
   lastName: "Lastname"
  },
  {
    id: 3,
   name:"thename",
   lastName: "Lastname"
  },
];

And a component that shows them in a table, and the table has the functionality to update this values. So the thing i want to do is to take this values, make a copy of them to the state of the component and update them with my inputs.

Copying:

const users= useSelector((state) => state.usersReducer);
const [userState, setUserState] = useState(users)
  useEffect(() => {
    setUserState(users); // if the users state from the redux grows
  }, [applicants]);

Mapping to display the data:

{ usersState.map( user=>{
<input onChange={(e) => handleChange(user)} value={user.name} >
})}

and with this handleChange

const handleChange = (data) => {
    setUserState((user) => {
      return [...user.filter((x) => x.id !== data.id), data];
    });
  };

but when I type in the input nothing happen... Because I could have multiple users, i'm mapping through them, I did forms before while learning, and never had this problem where the input doesn't change at all. But never had to do something like this, so i'm in trouble.

2 Answers

If you wanna update redux state also, you need to call dispatch to update redux state through reducer in handleChange function.

I have noticed two issues here in your snippet.

  • This component shouldn't have users as component state.

The selector is approximately equivalent to the mapStateToProps argument to connect conceptually. The selector will be called with the entire Redux store state as its only argument. The selector will be run whenever the function component renders (unless its reference hasn't changed since a previous render of the component so that a cached result can be returned by the hook without re-running the selector). useSelector() will also subscribe to the Redux store, and run your selector whenever an action is dispatched.

  • dispatch should be call in handleChange method to update redux state and re-render component

For example:

  const dispatch = useDispatch()

  const handleChange = (e, user) => {
    dispatch({
      type: 'UPDATE_USER',
      data: {
        ...user,
        name: e.target.value
      },
    })
Related