zadders
zadders

Reputation: 438

Edit method does not retrieve appropriate information [Error] React

I've developed a basic API using asp.net MVC that works as a basic User CRUD. (Create,Read, Update & Delete)

I have started to create a front end using ReactJS that has a Add user modal form, edit user modal and delete function.

enter image description here

The GET, POST and DELETE features all work, the only issue comes from the PUT. When I click on the Edit user modal, only the Id shows.

The code for the editUserModal.js is as follows:

const BASE_API_URL = `http://localhost:56062/api/users`;


export class EditUserModal extends Component{
    constructor(props){
        super(props);
        this.handleSubmit = this.handleSubmit.bind(this);
    }



    componentDidMount(){
        fetch(BASE_API_URL)
        .then(response => response.json())
        .then(data => {
        this.setState({deps:data});
        });
      }

    handleSubmit(event){
        event.preventDefault();
        fetch(BASE_API_URL,{
            method:'PUT',
            headers:{
                'Accept':'application/json',
                'Content-Type':'application/json'
            },
            body:JSON.stringify({

                Id:event.target.Id.value,
                firstName:event.target.firstName.value,
                lastName:event.target.lastName.value,
                Email:event.target.Email.value,
                mobileNumber:event.target.mobileNumber.value,
                dateOfBirth:event.target.dateOfBirth.value,
                lastModified:event.target.lastModified.value
            })
        })
        .then(res=> res.json())
        .then((result) =>
        {
            console.log(result);
        },
        (error) => {
            console.log('Failed')
        }
        )
    }

    render(){
        return(
            <Modal
            {...this.props}
            size="lg"
            aria-labelledby="contained-modal-title-vcenter"
            centered
          >
            <Modal.Header closeButton>
              <Modal.Title id="contained-modal-title-vcenter">
                Edit User
              </Modal.Title>
            </Modal.Header>
            <Modal.Body>
              <div className="editFormContainer">
                  <Row>
                      <Col sm={12}>
                          <Form onSubmit={this.handleSubmit}>

                          <Form.Group controlId="Id">
                                <Form.Label>User ID</Form.Label>
                                <Form.Control name="Id" disabled defaultValue = {this.props.userid} type="text" placeholder="Id" />
                              </Form.Group>
                              <Form.Group controlId="firstName">
                                <Form.Label>First Name</Form.Label>
                                <Form.Control name="firstName" required  type="text" defaultValue = {this.props.firstname} placeholder={this.props.firstname} />
                              </Form.Group>
                              <Form.Group controlId="lastName">
                                <Form.Label>Last Name</Form.Label>
                                <Form.Control name="lastName" required type="text" defaultValue = {this.props.lastname} placeholder="Last Name"  />
                              </Form.Group>
                              <Form.Group controlId="Email">
                                <Form.Label>Email address</Form.Label>
                                <Form.Control name="Email" required type="email" defaultValue = {this.props.useremail} placeholder="Email e.g. [email protected]" />
                              </Form.Group>
                              <Form.Group controlId="mobileNumber">
                                <Form.Label>Mobile Number</Form.Label>
                                <Form.Control name="mobileNumber" required type="text" defaultValue = {this.props.mobilenumber} placeholder="Mobile e.g. 0723218223 or +447236475886" />
                              </Form.Group>
                              <Form.Group controlId="dateOfBirth">
                                <Form.Label>Date of Birth</Form.Label>
                                <Form.Control name="dateOfBirth" required type="date" defaultValue = {this.props.dateofbirth} placeholder="Date of Birth e.g. 05-02-97" />
                              </Form.Group>
                            <Form.Group>
                                <Button variant="primary" type="submit">Edit User</Button>
                            </Form.Group>

                          </Form>
                      </Col>
                  </Row>
              </div>
            </Modal.Body>
            <Modal.Footer>
              <Button variant="danger" onClick={this.props.onHide}>Close</Button>
            </Modal.Footer>
          </Modal>
        )
    }
}

The code that contains the table (User.js) is as follows:

export class User extends Component {

    constructor(props){
        super(props);
        this.state = {users:[], addModalShow : false, editModalShow: false}

    }

    componentDidMount(){
        this.refreshList();

    }

    refreshList(){
      fetch(BASE_API_URL)
      .then(response=> response.json())
      .then(data => {
          this.setState({users:data})
      })
    }

    componentDidUpdate(){
      this.refreshList();

  }

    deleteUser(userid)
    {
      if(window.confirm('Are you sure?'))
      {
          fetch(`http://localhost:56062/api/users/`+userid,{
              method:'DELETE',
              header:{'Accept':'application/json',
              'Content-Type':'application/json'
          }
          })
      }
    }
render(){

    const {users, userid, firstname, lastname, useremail, mobilenumber, dateofbirth, lastmodified} = this.state;
    let addModalClose =() => this.setState({addModalShow:false});
    let editModalClose =() => this.setState({editModalShow:false});

    return(
        <div>
            <ButtonToolbar>
              <Button variant='outline-dark' onClick={()=> this.setState({addModalShow:true})}>
                  Add User
              </Button>
                <AddUserModal show={this.state.addModalShow} onHide={addModalClose} />
              </ButtonToolbar>

        <Table responsive striped hover size="sm" variant="dark" className="mt-4">
   <thead>
     <tr>
       <th>Id</th>
       <th>First Name</th>
       <th>Last Name</th>
       <th>Email</th>
       <th>Mobile Number</th>
       <th>Date of Birth</th>
       <th>Last Modified</th>
       <th>Edit</th>
       <th>Delete</th>
     </tr>
   </thead>
   <tbody>
        {users.map(user=> 
          <tr key = {user.Id}>
            <td>{user.Id}</td>
            <td>{user.firstName}</td>
            <td>{user.lastName}</td>
            <td>{user.Email}</td>
            <td>{user.mobileNumber}</td>
            <td>{user.dateOfBirth}</td>
            <td>{user.lastModified}</td>
            <td>
              <ButtonToolbar>
              <Button className="mr-2" variant="outline-light" onClick={()=> this.setState({editModalShow:true, userid:user.Id, mobilenumber:user.mobileNumber, dateofbirth:user.dateOfBirth, lastmodified:user.lastModified})}>
              Edit User
              </Button>
                <EditUserModal 
                show = {this.state.editModalShow} 
                onHide = {editModalClose} 
                userid = {userid} 
                firstname = {user.firstName}
                lastname = {user.lastName}
                useremail = {user.Email}
                mobilenumber = {user.mobileNumber}
                dateofbirth = {user.dateOfBirth}
                lastmodified = {user.lastModified} />
              </ButtonToolbar>
              </td>
              <td>
              <Button variant="outline-danger" onClick={()=> this.deleteUser(user.Id)} >Delete</Button>
              </td>

          </tr>
          )}
   </tbody>
 </Table>

 </div>
    )
}

}

So I think the issue lies within this section of code in the User.js

The code for the guide that I was looking at seemed to load all the appropriate fields when it was written like so,

<EditUserModal 
show = {this.state.editModalShow} 
onHide = {editModalClose} 
userid = {userid} 
firstname = {firstname}
lastname = {lastname}
useremail = {useremail}
mobilenumber = {mobilenumber }
dateofbirth = {dateofbirth }
lastmodified = {lastmodified } />

When the code was written like so, Only the Id and the mobilenumber will get loaded into the Edit User modal for some reason like so.

enter image description here

Whereas when I have the code like so, it displays the right Id for that column, but then displays all the information for the last inserted column like so.

<EditUserModal 
show = {this.state.editModalShow} 
onHide = {editModalClose} 
userid = {userid} 
firstname = {user.firstName}
lastname = {user.lastName}
useremail = {user.Email}
mobilenumber = {user.mobileNumber}
dateofbirth = {user.dateOfBirth}
lastmodified = {user.lastModified} />

enter image description here

The image above should be showing user 13, but instead displaying the rest of the info for the last input which is user 17.

enter image description here

Is there any specific reason as to why this is happening? maybe I am setting the states in a bad way?

======================== UPDATE =================================

I have now set a key prop within the component, yet the same thing is happening, only the id and mobile number appears in the text boxes when a edit modal is loaded up.

<EditUserModal 
              show = {this.state.editModalShow} 
              key = {userid}
              onHide = {editModalClose} 
              userid = {userid} 
              firstname = {firstname}
              lastname = {lastname}
              useremail = {useremail}
              mobilenumber = {mobilenumber}
              dateofbirth = {dateofbirth}
              lastmodified = {lastmodified} />

Upvotes: 0

Views: 51

Answers (1)

Kitanga Nday
Kitanga Nday

Reputation: 3565

Set a prop called key on the EditUserModal component and set it to the userId value.

You can read more about this here

Upvotes: 1

Related Questions