LDropl
LDropl

Reputation: 934

Issue with updating state in react-redux

There is a React component which contains list of users and form to invite a new user.

The problem is that after clicking on button "Invite User" I would like to see the invited user in the list of users ("currentUsers" in code below) without refreshing the page. But right now it happens only after I refresh the whole page.

when I'm trying to make a GET request to get all users right after inviteNewUser(data) (POST request) I'm getting the "old" user list without user which I just invited. So the "currentUsers" list is not immediately updated

Could someone help me to fix this issue ?

 export function MyForm({
  getUsers,
  inviteNewUser,
  userId,
  currentUsers
  }) {

    useEffect(() => {
      getUsers(userId);
    }, [userId]);

  function handleSendInvite(data) {
    inviteNewUser(data);
    getUsers(data.userId);
  }

  return (
  <>
      {currentUsers.map((user) => (
        <UserItem
          key={user.userId}
          user={user}
        />
      ))}
      <Button
        text="Invite User"
        onClick={() => {
            handleSendInvite({userId});
        }}
      />
  </>);
}


MyForm.propTypes = {
  getUsers: PropTypes.func.isRequired,
  inviteNewUser: PropTypes.func.isRequired,
  userId: PropTypes.number.isRequired,
  currentUsers: PropTypes.arrayOf(UserInfo),
};

const mapStateToProps = (state) => {
  const { id } = routerParamsSelector(state);
  const currentUsers = selectCurrentUsers(state);

  return {
    userId: parseInt(id, 10),
    currentUsers,
  };
};

const mapDispatchToProps = {
  getUsers,
  inviteNewUser
};

export default connect(mapStateToProps, mapDispatchToProps)(MyForm);

Upvotes: 0

Views: 26

Answers (2)

Vasile Coman
Vasile Coman

Reputation: 211

It should be user instead of userId as you access the property of the object in the function.


 

<Button text="Invite User" onClick={() => { handleSendInvite(user); }} />
------------------------------------------------------------------------

const handleSendInvite = async (data) {
  await inviteNewUser(data);
  getUsers(data.userId);
}

Upvotes: 1

Priyen Mehta
Priyen Mehta

Reputation: 1187

Try async and await, it works.

const handleSendInvite = async (data) {
  await inviteNewUser(data);
  getUsers(data.userId);
}

Upvotes: 1

Related Questions