0

I'm new to ReactJS. In my current project i'm populating data to HTML table from Mongo database and i have one column with checkbox(dynamically created based on db values) for select default profile(see below image). When checking one profile, particular profile in db will update with flag true and others are false

Profiles table

On checkbox click it will call API to update db flag. After update db i needs call a API to get data from same collection and update table. And i'm using following code.

I'm trying to use setState for render new data without refreshing page. I think i'm using setState without better understanding and i need to clear that. My questions are whats wrong with below code and is the any better way to achieve this scenario other than using setState ?

Profiles.jsx - render()

render() {
return (
  <React.Fragment>
    <div>
      <table className="table">
        <thead className="thead-dark">
          <tr>
            <th scope="col">ID</th>
            <th scope="col">Create Date</th>
            <th scope="col">Last Updated Date</th>
            <th scope="col">Default Profile</th>
            <th scope="col">Update</th>
            <th scope="col">Delete</th>
          </tr>
        </thead>
        <tbody>
          {this.state.profilesData.map(prof => (
            <tr key={prof._id}>
              <th scope="row">{prof._id}</th>
              <td>{prof.createdDate}</td>
              <td>{prof.lastUpdatedDate}</td>
              <td align="center">
                {prof.defaultProfile === true ? (
                  <input
                    name="defaultProfileCheck"
                    type="checkbox"
                    aria-label="Checkbox for following text input"
                    onChange={() => this.toggleDefault(prof._id)}
                    defaultChecked
                  />
                ) : (
                  <input
                    name="defaultProfileCheck"
                    type="checkbox"
                    aria-label="Checkbox for following text input"
                    onChange={() => this.toggleDefault(prof._id)}
                  />
                )}
              </td>
              <td>
                <button type="button" className="btn btn-warning">
                  Update
                </button>
              </td>
              <td>
                <button type="button" className="btn btn-danger">
                  Delete
                </button>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  </React.Fragment>
);

}

toggleDefault - onChange

state = {
  profilesData: []
};

async componentDidMount() {
const profiles = await getUserProfiles();  //Service Call
this.setState({ profilesData: profiles.data }); }

async toggleDefault(_id) {
if (window.confirm("Are you sure?")) {
  try {
    await setDefaultProfile(_id); //Service Call
  } catch (ex) {
    if (ex.response && ex.response.status === 404) toast.error(ex.message);
  }
  //toast.success("Done.");
  const profiles = await getUserProfiles(); //Service call for get updated data
  this.setState({ profilesData: profiles.data }); //Trying to setState for update view
} else {

}
}

Thank You.

1 Answer 1

2

this is exactly the usecase for ComponentDidUpdate.

Please go here: https://reactjs.org/docs/react-component.html#componentdidupdate There is an example, which I've included below that will help you to update the data as you wish to do.

componentDidUpdate(prevProps, prevState, snapshot)
componentDidUpdate(prevProps) {
  // Typical usage (don't forget to compare props):
  if (this.props.userID !== prevProps.userID) {
    this.fetchData(this.props.userID);
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much.. your answer helped me to solve my case. i use componentDidUpdate() as you said and change "defaultChecked" to checked={prof.defaultProfile}. thank you again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.