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
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.
