How to call ComponentDidMount() of different component from another component in react.js
Api.js
import React from 'react';
import './Api.scss';
import ProfileCard from 'components/Card/ProfileCard.jsx';
import Modal from 'react-awesome-modal';
class Api extends React.Component {
constructor(props) {
super(props);
this.state = {
title : '',
content: '',
img: '',
data:
}
}
OnFileChange = (event) => {
this.setState({img: event.target.files[0]});
}
onTitleChange = (event) => {
this.setState({title: event.target.value})
}
onContentChange = (event) => {
this.setState({content: event.target.value})
}
resetForm = () => {
document.getElementById('title').value = '';
document.getElementById('content').value = '';
document.getElementById('img').value = '';
}
openModal() {
this.setState({
visible : true
});
}
closeModal() {
this.setState({
visible : false
});
}
componentDidMount() {
fetch('http://127.0.0.1:8000/get_profile/')
.then(response => response.json())
.then(res => this.setState({ data: res }));
}
SubmitProfile = (event) => {
let formData = new FormData();
formData.append('img',this.state.img);
formData.append('title',this.state.title);
formData.append('content',this.state.content);
fetch('http://127.0.0.1:8000/post_profile/', {
method: 'post',
headers: {
Accept: 'application/json, text/plain, */*'
},
body:formData,
})
.then(response => response.json())
.then(res => {
if (res.code === 200){
this.componentDidMount()
this.resetForm()
this.closeModal()
}
console.log(res);
})
}
elasticSearch = (event) => {
fetch('http://127.0.0.1:8000/search/', {
method: 'post',
headers:{'Content-Type': 'application/json'},
body: JSON.stringify({
q: event.target.value
})
})
.then(response => response.json())
.then(res => {
console.log(res)
this.setState({ data: res })
});
}
render(){
return (
<div className="api-body">
<section>
<div className="tc pa2">
<input
type="button"
className="br2 center ph3 pv2 input-reset ba b--black bg-transparent grow pointer f6 dib"
value="Post"
onClick={() => this.openModal()}
/>
<input
className="db ma3 q center border-box hover-black w-100 measure ba b--black-20 pa2 br2 mb2"
type="text"
name="q"
id="q"
placeholder="search here .."
onChange = {this.elasticSearch}
/>
</div>
<Modal
visible={this.state.visible}
width="400"
height="300"
effect="fadeInDown"
onClickAway={() => this.closeModal()}
>
<div className="mv3 pa3">
<label className="db fw6 lh-copy f6" htmlFor="password">Title</label>
<input
className="db border-box hover-black w-100 measure ba b--black-20 pa2 br2 mb2"
type="text"
name="title"
id="title"
onChange={this.onTitleChange}
/>
</div>
<div className="mv3 pa3 mt-1">
<label htmlFor="comment" className="f6 b db mb2">Contents </label>
<textarea
id="content"
name="content"
className="db border-box hover-black w-100 measure ba b--black-20 pa2 br2 mb2"
aria-describedby="content-desc"
onChange={this.onContentChange}>
</textarea>
</div>
<div className="mv3 pa3 mt-1">
<input
type="file"
multiple = {false}
id="img"
name="img"
ref={(input) => { this.inpuElement = input; }}
accept=".jpg,.jpeg,.png,.pdf,.doc"
onChange={this.OnFileChange}
/>
<input
type="button"
className="br2 center ph3 pv2 input-reset ba b--black bg-transparent grow pointer f6 dib"
value="Submit"
onClick={this.SubmitProfile}
/>
</div>
</Modal>
</section>
<ProfileCard data={this.state.data} />
</div>
)
}
}
export default Api;
ProfileCard.js
import React from 'react';
class ProfileCard extends React.Component {
constructor(props){
super(props)
this.state = {
data :
}
}
deleteProfile = id => e => {
fetch('http://127.0.0.1:8000/delete_profile/', {
method: 'post',
headers:{'Content-Type': 'application/json'},
body: JSON.stringify({
id: id
})
})
.then(response => response.json())
.then(res => {
if (res.code === 200){
this.componentDidMount()
}
console.log(res)
})
}
render(){
return (
<div>
{
this.props.data.map((user,i) => {
return (
<article className='mw5 tc bg-white dib br3 pa3 ma3 pa4-ns mv3 ba b--black-10 shadow-5 pc-scroll pointer' key={i}>
<div className="tc">
<img
src={"http://127.0.0.1:8000" + user.photo}
className="br-100 h3 w3 dib"
alt="profile pic"
onDoubleClick = {this.deleteProfile(user.id)}
/>
<h1 className="f4">{user.title}</h1>
<hr className="mw3 bb bw1 b--black-10" />
</div>
<p className="lh-copy measure center f6 black-70">
{user.content}
</p>
</article>
);
})
}
</div>
);
}
}
export default ProfileCard;
in my ProfileCard there is a function deleteProfile as you can see and my componentDidMount
is on Api component. I want to call componentDidMount immediately after deleteProfile executes.
I am not able to find any proper way to do this.
if i will send componentDidMount directly also it won't work
because i am assigning res into the state.
reactjs
add a comment |
Api.js
import React from 'react';
import './Api.scss';
import ProfileCard from 'components/Card/ProfileCard.jsx';
import Modal from 'react-awesome-modal';
class Api extends React.Component {
constructor(props) {
super(props);
this.state = {
title : '',
content: '',
img: '',
data:
}
}
OnFileChange = (event) => {
this.setState({img: event.target.files[0]});
}
onTitleChange = (event) => {
this.setState({title: event.target.value})
}
onContentChange = (event) => {
this.setState({content: event.target.value})
}
resetForm = () => {
document.getElementById('title').value = '';
document.getElementById('content').value = '';
document.getElementById('img').value = '';
}
openModal() {
this.setState({
visible : true
});
}
closeModal() {
this.setState({
visible : false
});
}
componentDidMount() {
fetch('http://127.0.0.1:8000/get_profile/')
.then(response => response.json())
.then(res => this.setState({ data: res }));
}
SubmitProfile = (event) => {
let formData = new FormData();
formData.append('img',this.state.img);
formData.append('title',this.state.title);
formData.append('content',this.state.content);
fetch('http://127.0.0.1:8000/post_profile/', {
method: 'post',
headers: {
Accept: 'application/json, text/plain, */*'
},
body:formData,
})
.then(response => response.json())
.then(res => {
if (res.code === 200){
this.componentDidMount()
this.resetForm()
this.closeModal()
}
console.log(res);
})
}
elasticSearch = (event) => {
fetch('http://127.0.0.1:8000/search/', {
method: 'post',
headers:{'Content-Type': 'application/json'},
body: JSON.stringify({
q: event.target.value
})
})
.then(response => response.json())
.then(res => {
console.log(res)
this.setState({ data: res })
});
}
render(){
return (
<div className="api-body">
<section>
<div className="tc pa2">
<input
type="button"
className="br2 center ph3 pv2 input-reset ba b--black bg-transparent grow pointer f6 dib"
value="Post"
onClick={() => this.openModal()}
/>
<input
className="db ma3 q center border-box hover-black w-100 measure ba b--black-20 pa2 br2 mb2"
type="text"
name="q"
id="q"
placeholder="search here .."
onChange = {this.elasticSearch}
/>
</div>
<Modal
visible={this.state.visible}
width="400"
height="300"
effect="fadeInDown"
onClickAway={() => this.closeModal()}
>
<div className="mv3 pa3">
<label className="db fw6 lh-copy f6" htmlFor="password">Title</label>
<input
className="db border-box hover-black w-100 measure ba b--black-20 pa2 br2 mb2"
type="text"
name="title"
id="title"
onChange={this.onTitleChange}
/>
</div>
<div className="mv3 pa3 mt-1">
<label htmlFor="comment" className="f6 b db mb2">Contents </label>
<textarea
id="content"
name="content"
className="db border-box hover-black w-100 measure ba b--black-20 pa2 br2 mb2"
aria-describedby="content-desc"
onChange={this.onContentChange}>
</textarea>
</div>
<div className="mv3 pa3 mt-1">
<input
type="file"
multiple = {false}
id="img"
name="img"
ref={(input) => { this.inpuElement = input; }}
accept=".jpg,.jpeg,.png,.pdf,.doc"
onChange={this.OnFileChange}
/>
<input
type="button"
className="br2 center ph3 pv2 input-reset ba b--black bg-transparent grow pointer f6 dib"
value="Submit"
onClick={this.SubmitProfile}
/>
</div>
</Modal>
</section>
<ProfileCard data={this.state.data} />
</div>
)
}
}
export default Api;
ProfileCard.js
import React from 'react';
class ProfileCard extends React.Component {
constructor(props){
super(props)
this.state = {
data :
}
}
deleteProfile = id => e => {
fetch('http://127.0.0.1:8000/delete_profile/', {
method: 'post',
headers:{'Content-Type': 'application/json'},
body: JSON.stringify({
id: id
})
})
.then(response => response.json())
.then(res => {
if (res.code === 200){
this.componentDidMount()
}
console.log(res)
})
}
render(){
return (
<div>
{
this.props.data.map((user,i) => {
return (
<article className='mw5 tc bg-white dib br3 pa3 ma3 pa4-ns mv3 ba b--black-10 shadow-5 pc-scroll pointer' key={i}>
<div className="tc">
<img
src={"http://127.0.0.1:8000" + user.photo}
className="br-100 h3 w3 dib"
alt="profile pic"
onDoubleClick = {this.deleteProfile(user.id)}
/>
<h1 className="f4">{user.title}</h1>
<hr className="mw3 bb bw1 b--black-10" />
</div>
<p className="lh-copy measure center f6 black-70">
{user.content}
</p>
</article>
);
})
}
</div>
);
}
}
export default ProfileCard;
in my ProfileCard there is a function deleteProfile as you can see and my componentDidMount
is on Api component. I want to call componentDidMount immediately after deleteProfile executes.
I am not able to find any proper way to do this.
if i will send componentDidMount directly also it won't work
because i am assigning res into the state.
reactjs
3
You have XY problem. You don't have to call componentDidMount directly. Please, explain what you want to achieve.
– estus
Nov 20 '18 at 19:31
using componentDidMount() i am displaying all records. and after delete one also again i wants to display updated result so i am doing this way
– soubhagya
Nov 20 '18 at 19:33
Instead of callingcomponentDidMountyou should call afetchProfileDatamethod. Then bothcomponentDidMountanddeleteProfilecan call that method. Or, just have the API return the updated list in response to the delete call.
– Nick
Nov 20 '18 at 19:53
add a comment |
Api.js
import React from 'react';
import './Api.scss';
import ProfileCard from 'components/Card/ProfileCard.jsx';
import Modal from 'react-awesome-modal';
class Api extends React.Component {
constructor(props) {
super(props);
this.state = {
title : '',
content: '',
img: '',
data:
}
}
OnFileChange = (event) => {
this.setState({img: event.target.files[0]});
}
onTitleChange = (event) => {
this.setState({title: event.target.value})
}
onContentChange = (event) => {
this.setState({content: event.target.value})
}
resetForm = () => {
document.getElementById('title').value = '';
document.getElementById('content').value = '';
document.getElementById('img').value = '';
}
openModal() {
this.setState({
visible : true
});
}
closeModal() {
this.setState({
visible : false
});
}
componentDidMount() {
fetch('http://127.0.0.1:8000/get_profile/')
.then(response => response.json())
.then(res => this.setState({ data: res }));
}
SubmitProfile = (event) => {
let formData = new FormData();
formData.append('img',this.state.img);
formData.append('title',this.state.title);
formData.append('content',this.state.content);
fetch('http://127.0.0.1:8000/post_profile/', {
method: 'post',
headers: {
Accept: 'application/json, text/plain, */*'
},
body:formData,
})
.then(response => response.json())
.then(res => {
if (res.code === 200){
this.componentDidMount()
this.resetForm()
this.closeModal()
}
console.log(res);
})
}
elasticSearch = (event) => {
fetch('http://127.0.0.1:8000/search/', {
method: 'post',
headers:{'Content-Type': 'application/json'},
body: JSON.stringify({
q: event.target.value
})
})
.then(response => response.json())
.then(res => {
console.log(res)
this.setState({ data: res })
});
}
render(){
return (
<div className="api-body">
<section>
<div className="tc pa2">
<input
type="button"
className="br2 center ph3 pv2 input-reset ba b--black bg-transparent grow pointer f6 dib"
value="Post"
onClick={() => this.openModal()}
/>
<input
className="db ma3 q center border-box hover-black w-100 measure ba b--black-20 pa2 br2 mb2"
type="text"
name="q"
id="q"
placeholder="search here .."
onChange = {this.elasticSearch}
/>
</div>
<Modal
visible={this.state.visible}
width="400"
height="300"
effect="fadeInDown"
onClickAway={() => this.closeModal()}
>
<div className="mv3 pa3">
<label className="db fw6 lh-copy f6" htmlFor="password">Title</label>
<input
className="db border-box hover-black w-100 measure ba b--black-20 pa2 br2 mb2"
type="text"
name="title"
id="title"
onChange={this.onTitleChange}
/>
</div>
<div className="mv3 pa3 mt-1">
<label htmlFor="comment" className="f6 b db mb2">Contents </label>
<textarea
id="content"
name="content"
className="db border-box hover-black w-100 measure ba b--black-20 pa2 br2 mb2"
aria-describedby="content-desc"
onChange={this.onContentChange}>
</textarea>
</div>
<div className="mv3 pa3 mt-1">
<input
type="file"
multiple = {false}
id="img"
name="img"
ref={(input) => { this.inpuElement = input; }}
accept=".jpg,.jpeg,.png,.pdf,.doc"
onChange={this.OnFileChange}
/>
<input
type="button"
className="br2 center ph3 pv2 input-reset ba b--black bg-transparent grow pointer f6 dib"
value="Submit"
onClick={this.SubmitProfile}
/>
</div>
</Modal>
</section>
<ProfileCard data={this.state.data} />
</div>
)
}
}
export default Api;
ProfileCard.js
import React from 'react';
class ProfileCard extends React.Component {
constructor(props){
super(props)
this.state = {
data :
}
}
deleteProfile = id => e => {
fetch('http://127.0.0.1:8000/delete_profile/', {
method: 'post',
headers:{'Content-Type': 'application/json'},
body: JSON.stringify({
id: id
})
})
.then(response => response.json())
.then(res => {
if (res.code === 200){
this.componentDidMount()
}
console.log(res)
})
}
render(){
return (
<div>
{
this.props.data.map((user,i) => {
return (
<article className='mw5 tc bg-white dib br3 pa3 ma3 pa4-ns mv3 ba b--black-10 shadow-5 pc-scroll pointer' key={i}>
<div className="tc">
<img
src={"http://127.0.0.1:8000" + user.photo}
className="br-100 h3 w3 dib"
alt="profile pic"
onDoubleClick = {this.deleteProfile(user.id)}
/>
<h1 className="f4">{user.title}</h1>
<hr className="mw3 bb bw1 b--black-10" />
</div>
<p className="lh-copy measure center f6 black-70">
{user.content}
</p>
</article>
);
})
}
</div>
);
}
}
export default ProfileCard;
in my ProfileCard there is a function deleteProfile as you can see and my componentDidMount
is on Api component. I want to call componentDidMount immediately after deleteProfile executes.
I am not able to find any proper way to do this.
if i will send componentDidMount directly also it won't work
because i am assigning res into the state.
reactjs
Api.js
import React from 'react';
import './Api.scss';
import ProfileCard from 'components/Card/ProfileCard.jsx';
import Modal from 'react-awesome-modal';
class Api extends React.Component {
constructor(props) {
super(props);
this.state = {
title : '',
content: '',
img: '',
data:
}
}
OnFileChange = (event) => {
this.setState({img: event.target.files[0]});
}
onTitleChange = (event) => {
this.setState({title: event.target.value})
}
onContentChange = (event) => {
this.setState({content: event.target.value})
}
resetForm = () => {
document.getElementById('title').value = '';
document.getElementById('content').value = '';
document.getElementById('img').value = '';
}
openModal() {
this.setState({
visible : true
});
}
closeModal() {
this.setState({
visible : false
});
}
componentDidMount() {
fetch('http://127.0.0.1:8000/get_profile/')
.then(response => response.json())
.then(res => this.setState({ data: res }));
}
SubmitProfile = (event) => {
let formData = new FormData();
formData.append('img',this.state.img);
formData.append('title',this.state.title);
formData.append('content',this.state.content);
fetch('http://127.0.0.1:8000/post_profile/', {
method: 'post',
headers: {
Accept: 'application/json, text/plain, */*'
},
body:formData,
})
.then(response => response.json())
.then(res => {
if (res.code === 200){
this.componentDidMount()
this.resetForm()
this.closeModal()
}
console.log(res);
})
}
elasticSearch = (event) => {
fetch('http://127.0.0.1:8000/search/', {
method: 'post',
headers:{'Content-Type': 'application/json'},
body: JSON.stringify({
q: event.target.value
})
})
.then(response => response.json())
.then(res => {
console.log(res)
this.setState({ data: res })
});
}
render(){
return (
<div className="api-body">
<section>
<div className="tc pa2">
<input
type="button"
className="br2 center ph3 pv2 input-reset ba b--black bg-transparent grow pointer f6 dib"
value="Post"
onClick={() => this.openModal()}
/>
<input
className="db ma3 q center border-box hover-black w-100 measure ba b--black-20 pa2 br2 mb2"
type="text"
name="q"
id="q"
placeholder="search here .."
onChange = {this.elasticSearch}
/>
</div>
<Modal
visible={this.state.visible}
width="400"
height="300"
effect="fadeInDown"
onClickAway={() => this.closeModal()}
>
<div className="mv3 pa3">
<label className="db fw6 lh-copy f6" htmlFor="password">Title</label>
<input
className="db border-box hover-black w-100 measure ba b--black-20 pa2 br2 mb2"
type="text"
name="title"
id="title"
onChange={this.onTitleChange}
/>
</div>
<div className="mv3 pa3 mt-1">
<label htmlFor="comment" className="f6 b db mb2">Contents </label>
<textarea
id="content"
name="content"
className="db border-box hover-black w-100 measure ba b--black-20 pa2 br2 mb2"
aria-describedby="content-desc"
onChange={this.onContentChange}>
</textarea>
</div>
<div className="mv3 pa3 mt-1">
<input
type="file"
multiple = {false}
id="img"
name="img"
ref={(input) => { this.inpuElement = input; }}
accept=".jpg,.jpeg,.png,.pdf,.doc"
onChange={this.OnFileChange}
/>
<input
type="button"
className="br2 center ph3 pv2 input-reset ba b--black bg-transparent grow pointer f6 dib"
value="Submit"
onClick={this.SubmitProfile}
/>
</div>
</Modal>
</section>
<ProfileCard data={this.state.data} />
</div>
)
}
}
export default Api;
ProfileCard.js
import React from 'react';
class ProfileCard extends React.Component {
constructor(props){
super(props)
this.state = {
data :
}
}
deleteProfile = id => e => {
fetch('http://127.0.0.1:8000/delete_profile/', {
method: 'post',
headers:{'Content-Type': 'application/json'},
body: JSON.stringify({
id: id
})
})
.then(response => response.json())
.then(res => {
if (res.code === 200){
this.componentDidMount()
}
console.log(res)
})
}
render(){
return (
<div>
{
this.props.data.map((user,i) => {
return (
<article className='mw5 tc bg-white dib br3 pa3 ma3 pa4-ns mv3 ba b--black-10 shadow-5 pc-scroll pointer' key={i}>
<div className="tc">
<img
src={"http://127.0.0.1:8000" + user.photo}
className="br-100 h3 w3 dib"
alt="profile pic"
onDoubleClick = {this.deleteProfile(user.id)}
/>
<h1 className="f4">{user.title}</h1>
<hr className="mw3 bb bw1 b--black-10" />
</div>
<p className="lh-copy measure center f6 black-70">
{user.content}
</p>
</article>
);
})
}
</div>
);
}
}
export default ProfileCard;
in my ProfileCard there is a function deleteProfile as you can see and my componentDidMount
is on Api component. I want to call componentDidMount immediately after deleteProfile executes.
I am not able to find any proper way to do this.
if i will send componentDidMount directly also it won't work
because i am assigning res into the state.
reactjs
reactjs
edited Nov 20 '18 at 19:41
Sung M. Kim
17.6k33111161
17.6k33111161
asked Nov 20 '18 at 19:19
soubhagyasoubhagya
917
917
3
You have XY problem. You don't have to call componentDidMount directly. Please, explain what you want to achieve.
– estus
Nov 20 '18 at 19:31
using componentDidMount() i am displaying all records. and after delete one also again i wants to display updated result so i am doing this way
– soubhagya
Nov 20 '18 at 19:33
Instead of callingcomponentDidMountyou should call afetchProfileDatamethod. Then bothcomponentDidMountanddeleteProfilecan call that method. Or, just have the API return the updated list in response to the delete call.
– Nick
Nov 20 '18 at 19:53
add a comment |
3
You have XY problem. You don't have to call componentDidMount directly. Please, explain what you want to achieve.
– estus
Nov 20 '18 at 19:31
using componentDidMount() i am displaying all records. and after delete one also again i wants to display updated result so i am doing this way
– soubhagya
Nov 20 '18 at 19:33
Instead of callingcomponentDidMountyou should call afetchProfileDatamethod. Then bothcomponentDidMountanddeleteProfilecan call that method. Or, just have the API return the updated list in response to the delete call.
– Nick
Nov 20 '18 at 19:53
3
3
You have XY problem. You don't have to call componentDidMount directly. Please, explain what you want to achieve.
– estus
Nov 20 '18 at 19:31
You have XY problem. You don't have to call componentDidMount directly. Please, explain what you want to achieve.
– estus
Nov 20 '18 at 19:31
using componentDidMount() i am displaying all records. and after delete one also again i wants to display updated result so i am doing this way
– soubhagya
Nov 20 '18 at 19:33
using componentDidMount() i am displaying all records. and after delete one also again i wants to display updated result so i am doing this way
– soubhagya
Nov 20 '18 at 19:33
Instead of calling
componentDidMount you should call a fetchProfileData method. Then both componentDidMount and deleteProfile can call that method. Or, just have the API return the updated list in response to the delete call.– Nick
Nov 20 '18 at 19:53
Instead of calling
componentDidMount you should call a fetchProfileData method. Then both componentDidMount and deleteProfile can call that method. Or, just have the API return the updated list in response to the delete call.– Nick
Nov 20 '18 at 19:53
add a comment |
2 Answers
2
active
oldest
votes
@estus is correct in the comments. You shouldn't - and don't - need to call componentDidMount directly but you can call a function from the owner component.
First, we create a new function for fetching the profile. This can still be called in componentDidMount.
fetchProfile() {
fetch('http://127.0.0.1:8000/get_profile/')
.then(response => response.json())
.then(res => this.setState({ data: res }));
}
componentDidMount() {
this.fetchProfile()
}
We then pass this function as a prop into <ProfileCard />
<ProfileCard data={ this.state.data } onProfileDelete={ () => this.fetchProfile() } />
Finally, we call this prop after we've deleted a profile within ProfileCard.
deleteProfile = id => e => {
...
.then(res => {
if (res.code === 200) {
const { onProfileDelete } = this.props
onProfileDelete() // call prop func instead
}
console.log(res)
})
}
Thanks .. that work nicely
– soubhagya
Nov 20 '18 at 20:06
add a comment |
componentDidMount is lifecycle hook. It isn't expected to be called directly. A semantically correct way is to provide a method that will be reused in both places:
componentDidMount() {
this.fetchData();
}
fetchData() {
return fetch('http://127.0.0.1:8000/get_profile/')
.then(response => response.json())
.then(res => this.setState({ data: res }));
}
SubmitProfile = (event) => {
...
.then(res => {
if (res.code === 200){
return this.fetchData()
...
}
This also benefits testability. fetchData can be tested separately from component lifecycle. Also, methods should return promises, all promises should be chained.
The problem here is the separation of concerns. ProfileCard should be dumb component and delegate all the work to a parent. This method belongs to parent Api component:
deleteProfile = id => {
fetch('http://127.0.0.1:8000/delete_profile/', ...)
...
.then(res => {
if (res.code === 200){
this.fetchData()
}
})
}
It should be passed to child component:
<ProfileCard onDelete={this.deleteProfile} />
And used in child component as a prop:
<img
src={"http://127.0.0.1:8000" + user.photo}
className="br-100 h3 w3 dib"
alt="profile pic"
onDoubleClick={() => this.props.onDelete(user.id)}
/>
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53400065%2fhow-to-call-componentdidmount-of-different-component-from-another-component-in%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
@estus is correct in the comments. You shouldn't - and don't - need to call componentDidMount directly but you can call a function from the owner component.
First, we create a new function for fetching the profile. This can still be called in componentDidMount.
fetchProfile() {
fetch('http://127.0.0.1:8000/get_profile/')
.then(response => response.json())
.then(res => this.setState({ data: res }));
}
componentDidMount() {
this.fetchProfile()
}
We then pass this function as a prop into <ProfileCard />
<ProfileCard data={ this.state.data } onProfileDelete={ () => this.fetchProfile() } />
Finally, we call this prop after we've deleted a profile within ProfileCard.
deleteProfile = id => e => {
...
.then(res => {
if (res.code === 200) {
const { onProfileDelete } = this.props
onProfileDelete() // call prop func instead
}
console.log(res)
})
}
Thanks .. that work nicely
– soubhagya
Nov 20 '18 at 20:06
add a comment |
@estus is correct in the comments. You shouldn't - and don't - need to call componentDidMount directly but you can call a function from the owner component.
First, we create a new function for fetching the profile. This can still be called in componentDidMount.
fetchProfile() {
fetch('http://127.0.0.1:8000/get_profile/')
.then(response => response.json())
.then(res => this.setState({ data: res }));
}
componentDidMount() {
this.fetchProfile()
}
We then pass this function as a prop into <ProfileCard />
<ProfileCard data={ this.state.data } onProfileDelete={ () => this.fetchProfile() } />
Finally, we call this prop after we've deleted a profile within ProfileCard.
deleteProfile = id => e => {
...
.then(res => {
if (res.code === 200) {
const { onProfileDelete } = this.props
onProfileDelete() // call prop func instead
}
console.log(res)
})
}
Thanks .. that work nicely
– soubhagya
Nov 20 '18 at 20:06
add a comment |
@estus is correct in the comments. You shouldn't - and don't - need to call componentDidMount directly but you can call a function from the owner component.
First, we create a new function for fetching the profile. This can still be called in componentDidMount.
fetchProfile() {
fetch('http://127.0.0.1:8000/get_profile/')
.then(response => response.json())
.then(res => this.setState({ data: res }));
}
componentDidMount() {
this.fetchProfile()
}
We then pass this function as a prop into <ProfileCard />
<ProfileCard data={ this.state.data } onProfileDelete={ () => this.fetchProfile() } />
Finally, we call this prop after we've deleted a profile within ProfileCard.
deleteProfile = id => e => {
...
.then(res => {
if (res.code === 200) {
const { onProfileDelete } = this.props
onProfileDelete() // call prop func instead
}
console.log(res)
})
}
@estus is correct in the comments. You shouldn't - and don't - need to call componentDidMount directly but you can call a function from the owner component.
First, we create a new function for fetching the profile. This can still be called in componentDidMount.
fetchProfile() {
fetch('http://127.0.0.1:8000/get_profile/')
.then(response => response.json())
.then(res => this.setState({ data: res }));
}
componentDidMount() {
this.fetchProfile()
}
We then pass this function as a prop into <ProfileCard />
<ProfileCard data={ this.state.data } onProfileDelete={ () => this.fetchProfile() } />
Finally, we call this prop after we've deleted a profile within ProfileCard.
deleteProfile = id => e => {
...
.then(res => {
if (res.code === 200) {
const { onProfileDelete } = this.props
onProfileDelete() // call prop func instead
}
console.log(res)
})
}
answered Nov 20 '18 at 19:59
Cameron DownerCameron Downer
626419
626419
Thanks .. that work nicely
– soubhagya
Nov 20 '18 at 20:06
add a comment |
Thanks .. that work nicely
– soubhagya
Nov 20 '18 at 20:06
Thanks .. that work nicely
– soubhagya
Nov 20 '18 at 20:06
Thanks .. that work nicely
– soubhagya
Nov 20 '18 at 20:06
add a comment |
componentDidMount is lifecycle hook. It isn't expected to be called directly. A semantically correct way is to provide a method that will be reused in both places:
componentDidMount() {
this.fetchData();
}
fetchData() {
return fetch('http://127.0.0.1:8000/get_profile/')
.then(response => response.json())
.then(res => this.setState({ data: res }));
}
SubmitProfile = (event) => {
...
.then(res => {
if (res.code === 200){
return this.fetchData()
...
}
This also benefits testability. fetchData can be tested separately from component lifecycle. Also, methods should return promises, all promises should be chained.
The problem here is the separation of concerns. ProfileCard should be dumb component and delegate all the work to a parent. This method belongs to parent Api component:
deleteProfile = id => {
fetch('http://127.0.0.1:8000/delete_profile/', ...)
...
.then(res => {
if (res.code === 200){
this.fetchData()
}
})
}
It should be passed to child component:
<ProfileCard onDelete={this.deleteProfile} />
And used in child component as a prop:
<img
src={"http://127.0.0.1:8000" + user.photo}
className="br-100 h3 w3 dib"
alt="profile pic"
onDoubleClick={() => this.props.onDelete(user.id)}
/>
add a comment |
componentDidMount is lifecycle hook. It isn't expected to be called directly. A semantically correct way is to provide a method that will be reused in both places:
componentDidMount() {
this.fetchData();
}
fetchData() {
return fetch('http://127.0.0.1:8000/get_profile/')
.then(response => response.json())
.then(res => this.setState({ data: res }));
}
SubmitProfile = (event) => {
...
.then(res => {
if (res.code === 200){
return this.fetchData()
...
}
This also benefits testability. fetchData can be tested separately from component lifecycle. Also, methods should return promises, all promises should be chained.
The problem here is the separation of concerns. ProfileCard should be dumb component and delegate all the work to a parent. This method belongs to parent Api component:
deleteProfile = id => {
fetch('http://127.0.0.1:8000/delete_profile/', ...)
...
.then(res => {
if (res.code === 200){
this.fetchData()
}
})
}
It should be passed to child component:
<ProfileCard onDelete={this.deleteProfile} />
And used in child component as a prop:
<img
src={"http://127.0.0.1:8000" + user.photo}
className="br-100 h3 w3 dib"
alt="profile pic"
onDoubleClick={() => this.props.onDelete(user.id)}
/>
add a comment |
componentDidMount is lifecycle hook. It isn't expected to be called directly. A semantically correct way is to provide a method that will be reused in both places:
componentDidMount() {
this.fetchData();
}
fetchData() {
return fetch('http://127.0.0.1:8000/get_profile/')
.then(response => response.json())
.then(res => this.setState({ data: res }));
}
SubmitProfile = (event) => {
...
.then(res => {
if (res.code === 200){
return this.fetchData()
...
}
This also benefits testability. fetchData can be tested separately from component lifecycle. Also, methods should return promises, all promises should be chained.
The problem here is the separation of concerns. ProfileCard should be dumb component and delegate all the work to a parent. This method belongs to parent Api component:
deleteProfile = id => {
fetch('http://127.0.0.1:8000/delete_profile/', ...)
...
.then(res => {
if (res.code === 200){
this.fetchData()
}
})
}
It should be passed to child component:
<ProfileCard onDelete={this.deleteProfile} />
And used in child component as a prop:
<img
src={"http://127.0.0.1:8000" + user.photo}
className="br-100 h3 w3 dib"
alt="profile pic"
onDoubleClick={() => this.props.onDelete(user.id)}
/>
componentDidMount is lifecycle hook. It isn't expected to be called directly. A semantically correct way is to provide a method that will be reused in both places:
componentDidMount() {
this.fetchData();
}
fetchData() {
return fetch('http://127.0.0.1:8000/get_profile/')
.then(response => response.json())
.then(res => this.setState({ data: res }));
}
SubmitProfile = (event) => {
...
.then(res => {
if (res.code === 200){
return this.fetchData()
...
}
This also benefits testability. fetchData can be tested separately from component lifecycle. Also, methods should return promises, all promises should be chained.
The problem here is the separation of concerns. ProfileCard should be dumb component and delegate all the work to a parent. This method belongs to parent Api component:
deleteProfile = id => {
fetch('http://127.0.0.1:8000/delete_profile/', ...)
...
.then(res => {
if (res.code === 200){
this.fetchData()
}
})
}
It should be passed to child component:
<ProfileCard onDelete={this.deleteProfile} />
And used in child component as a prop:
<img
src={"http://127.0.0.1:8000" + user.photo}
className="br-100 h3 w3 dib"
alt="profile pic"
onDoubleClick={() => this.props.onDelete(user.id)}
/>
answered Nov 20 '18 at 19:59
estusestus
74.1k22108224
74.1k22108224
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53400065%2fhow-to-call-componentdidmount-of-different-component-from-another-component-in%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
3
You have XY problem. You don't have to call componentDidMount directly. Please, explain what you want to achieve.
– estus
Nov 20 '18 at 19:31
using componentDidMount() i am displaying all records. and after delete one also again i wants to display updated result so i am doing this way
– soubhagya
Nov 20 '18 at 19:33
Instead of calling
componentDidMountyou should call afetchProfileDatamethod. Then bothcomponentDidMountanddeleteProfilecan call that method. Or, just have the API return the updated list in response to the delete call.– Nick
Nov 20 '18 at 19:53