Reputation: 2665
Context:
I'm working on vanilla React and React Bootstrap (no redux) project to manage roles in my department. The list of roles is not really relevant but for context imagine: Admin, Manager, Trainer, and so on.
I have a parent component <RoleContainer key={role} role={role} />
element that has the following state:
this.state = {
collapsed: true,
roleAttributes: [],
roleMembers: [],
isLoading: true,
};
Inside <RoleContainer />
, there is a <table/>
element that contains a roleMembers.map
to loop through the roleMembers
and render the table rows dynamically. So, for each role member, you get a table row.
The Problem:
I have a component called <CreateMemberModal role={role} roleAttributes={roleAttributes} />
which is a child component of <RoleContainer />
and it allows the user to POST
a new roleMember
.
Currently, I have to POST
the new roleMember
into the DB and then reload the page so the changes can reflect.
Is there an accepted way (not an anti-pattern or bad practice) without redux to update the roleMembers
state property of the <RoleContainer />
component from within the child <CreateMemberModal />
when I POST
a new user?
It would allow me to re-render just the <RoleContainer />
that had a new role member, instead of reloading the entire page.
Upvotes: 1
Views: 1220
Reputation: 34107
Add a method in <RoleContainer />
to update roleMembers
// bind this in constructor
updateRoleMembers(newRoleMember) {
this.setState((prevState)=> {
return {roleMembers : prevState.roleMembers.concat([newRoleMember])}
}
}
Now pass this method to CreateMemberModal
<CreateMemberModal role={role} roleAttributes={roleAttributes} updateRoleMembers={this.updateRoleMembers} />
call like this.props.updateRoleMembers(NEW ROLE MEMBER)
in <CreateMemberModal
component whenever you have the new member role details
Is there any documentation on how to do this that you can point me to? When you say provide a callback, do you mean I pass a function through a prop from the parent to the child?
Check the react docs here
Upvotes: 1
Reputation: 629
You can get use of the callBack function... I am assuming your structure will be something like this...
export class RoleContainer extends React.Component {
this.state = {
collapsed: true,
roleAttributes: [],
roleMembers: [],
isLoading: true,
};
yourApiCallToUpdateRoleMembers = () => {
apiCall().then(response => {
this.setState({
roleMembers: response // assuming response has the data
})
})
}
render(){
return <>
<table>
{this.state.roleMembers.map(element => <tr></tr>)}
</table>
<CreateMemberModal role={role} roleAttributes={roleAttributes} /> // instead of this add a callback function also
<CreateMemberModal role={role} roleAttributes={roleAttributes} successCb={yourApiCallToUpdateRoleMembers} />
</>
}
}
And your child component is having the post call to update the data
export function CreateMemberModal(props) {
makePostCall = () => {
apiCall().then(response => {
props.successCb()
})
}
}
Upvotes: 1