In order to allow my parent component
to reach values of my child component
( Display
), I started working with the createRef () API that came out in this 16.3 patch.
Following the example "Adding a Ref to a Class Component" that is in this documentation I I made the following changes to my code:
class JsonFetcher extends Component {
constructor(props) {
super(props);
this.child = React.createRef();
this.state = {
data: [],
}
}
componentDidMount() {
this.updateContent(this.props.mainUrl)
}
updateContent(mainUrl){
fetch(mainUrl)
.then((responseJsonAnyUrl) => responseJsonAnyUrl.json())
.then((responseJsonAnyUrl) => {
this.setState({
mainUrl: mainUrl,
jsonObject: responseJsonAnyUrl
},
function () {
this.timeout = setTimeout(
function(){
//let ind = this.child.current.getCurrentIndex
//tyring to get values from child...
//if index === length-1
this.updateContent(mainUrl)
//else
//retry this function in 5 seconds
//
}.bind(this, mainUrl)
,
20000)
}.bind(this))
})
}
interpretJson() {
/*
*some code
*/
return(
<Display content={contentListArray} ref={this.child}/>
)
}
render() {
if(this.state.jsonObject){
return (
<div>
<div> {this.interpretJson()} </div>
</div>
)
}else
return(
null
)
}
}
So I create ref in the constructor, associate it with the child component Display
in the final function interpretJson()
and try to use a method of child
in my function of timeOut()
, but I get the error :
"TypeError: Can not read property 'getCurrentIndex' of null "
What am I doing wrong not to be able to call the methods of Display
to simulate the pseudo-code I have in comment?
EDIT :
Here is Display
class Display extends Component{
constructor(props){
console.log('Display constructor was called')
super(props);
this.state = {
contentIndex: -1
}
this.switchContent = this.switchContent.bind(this)
}
/*some methods */
getCurrentIndex(){
return this.state.contentIndex
}
getZoneLengths(){
let zoneLengths = []
this.props.content.map((zoneX, index) => {
zoneLengths.push(zoneX.length)
})
return zoneLengths
}
render(){ /* some code */ }