I am encountering a very wierd issue with React createRef
I call a ref and it only works in an else branch of an if/else statement.
if I remove the if statement, the ref does not work, and if the function goes to the IF path, it does not work too.
Here is a snippet.
sendFetch("/api/cases?q=" + JSON.stringify(query_payload), "", "GET").then(
data => {
this.fetchedData = data;
console.log(data.count + " results found")
//populate the table with results
if (data.count === "0" || data.status === "failed") {
console.log("NOT FOUND")
this.tableRef.current.loadTablewithNewData(false)
//NOT WORKING
} else {
//reload the table component with the new data
this.tableRef.current.loadTablewithNewData(data.context)
//WORKING
}
}
)
When the IF path is followed, or I remove the if/else alltogether and call the ref function right away, REACT shows this error × Unhandled Rejection (TypeError): Cannot read property 'loadTablewithNewData' of null
Did you check to see if the element you've added a ref to actually exists in the DOM when you make the request?
Unhandled Rejection (TypeError): Cannot read property 'loadTablewithNewData' of null
This error is given only if the element is not present in the DOM when you try to access it. The code you've posted here works as expected. Check if the element exists before you try to manipulate it directly in the DOM
if(this.tableRef.current){ // It would be null if it doesn't exist
if (data.count === "0" || data.status === "failed") {
console.log("NOT FOUND")
this.tableRef.current.loadTablewithNewData(false)
} else {
//reload the table component with the new data
this.tableRef.current.loadTablewithNewData(data.context)
}
} else {
console.log('Table not present in the DOM')
}