I am trying to update a parent components state properties from a child component. I am writing a small POC that will send a request to get some data, update the parents state
properties each time I send the request, and have another child component render the parents state
properties into a graph (using CanvasJS). Anyway, I have followed a few tutorials and they seem to be showing the same thing. But when I implement it, I get the Unhandled Rejection (TypeError): this.props.callbackFunction is not a function
error. Here is my code:
Parent
import React, { Component } from "react";
import H2Request from "./myRequest";
class AllComponents extends Component {
state = {
items: this.props.value
};
callbackFunction = childData => {
this.setState({ items: childData });
};
render() {
return (
<div>
<MyRequest dataFromParent={this.state.items} />
</div>
);
}
}
export default AllComponents;
Child
import React, { Component } from "react";
import axios from "axios";
import "../App.css";
class MyRequest extends Component {
handleClick = () => {
axios.get("http://localhost:8003").then(response => {
this.props.callbackFunction(response.data);
});
};
render() {
return (
<div className="button_container">
<button className="button" onClick={() => this.handleClick()}>
Refresh
</button>
<h1>
Items:
{JSON.stringify(this.props.dataFromParent, null, 2)}
</h1>
</div>
);
}
}
export default MyRequest;
But when I click my Refresh
button, I get the following error:
Unhandled Rejection (TypeError): this.props.callbackFunction is not a function
(anonymous function)
src/components/h2Request.jsx:10
7 | axios.get("http://localhost:8003").then(response => {
> 8 | this.props.callbackFunction(response.data);
9 | ^ });
10 | };
I have tried adding a .bind(this)
on to the end of the callbackFunction
call, but same thing.
In you AllComponent, you have defined the function but not included in the child component props
import React, { Component } from "react";
import H2Request from "./myRequest";
class AllComponents extends Component {
state = {
items: this.props.value
};
callbackFunction = childData => {
this.setState({ items: childData });
};
render() {
return (
<div>
<MyRequest dataFromParent={this.state.items} /> // see no callBackFunction in props
</div>
);
}
}
export default AllComponents;
Change your parent component to, (add callbackFunction as props, so it can be accessed in the child component as this.props.callbackFunction()
)
import React, { Component } from "react";
import H2Request from "./myRequest";
class AllComponents extends Component {
state = {
items: this.props.value
};
callbackFunction = childData => {
this.setState({ items: childData });
};
render() {
return (
<div>
<MyRequest dataFromParent={this.state.items} callbackFunction={()=>this.callbackFunction()} /> // add callback as props in here
</div>
);
}
}
export default AllComponents;