0

I've implemented user list and can delete users dispatching action deleteUser(). Now I add user but once I click add button the data is not mapped in the list. this is a reducer:

case ADD_USERS:
          const newId = state.users[state.users.length-1] + 1
          return {
              ...state,
              users: [
                ...state.users,
                {
                  id: newId,
                  name: action.payload
                }
              ],
              loading: false
  
          }

initial state consists of 2 objects and loading key. The action function is simple:

export function addUser (name) {
  return {
    type: ADD_USERS,
    payload: name
  }

and the component is there:

const mapStateToProps = (state) => ({ users: state.users });
const mapDispatchToProps = (dispatch) => {
  return {
    deleteUser: id => {
      dispatch(deleteUser(id))
    },
    addUser: name => {
      dispatch(addUsers(name))
    }
  }
     
};


const Users = (props) => {
  const { users } = props.users;


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

  return (
    <>
    <input type='text' placeholder='name..'/>
    <button onClick={() => props.addUser(name)}>add</button>
      <h2>Users</h2>
      {users.map((user) => {
        return (
          <div className="d-flex justify-content-between align-items-center mb-1">
            <li>{user.name}</li>
            <button onClick={() => props.deleteUser(user.id)}>x</button>
           
          </div>
        );
      })}
    </>
  );
};
}

I consider getUsers don't work or I can be wrong. cause I map state to props and display the data inside

  • {user.name}
  • I think it should work same with getUsers()
    Xena
    • 379
    • 3
    • 9
    • 2
      *Typo:* Seems like you have incorrect mapping: `addUser: name => { dispatch(deleteUser(name)) }`. It should be mapped with, e.g, `addUser(name)`. – Ajeet Shah Mar 30 '21 at 20:21

    2 Answers2

    0

    Maybe this is not the only one issue, but at least this looks strange to me:

    const { users } = props.users;
    

    Because, with the line above you are creating a constant with value from props.users.users. You have not shown how you use the Users component and what it gets from outside, but this looks at least strange to me.

    Diceros
    • 83
    • 6
    0
    <button onClick={() => props.addUser(name)}>add</button>
    

    Your button calls addUser with a variable name, but that variable doesn't exist!

    You need to change your input into a controlled component so that you can call addUser with the name from the input field.

    const [name, setName] = useState("");
    
    return (
      <>
        <input
          type="text"
          placeholder="name.."
          value={name}
          onChange={(e) => setName(e.target.value)}
        />
        <button onClick={() => props.addUser(name)}>add</button>
    ...
    
    Linda Paiste
    • 38,446
    • 6
    • 64
    • 102