Most examples shows ReactJS fetch() in componentDidMount. In my example, I need a fetch as part of a state change received from another component, after initialization (initially my component is empty). I currently do it in render() which is always called on a state change.
But something's wrong: the Fetch works and the render() is called on the state change, but return <div>..</div> doesn't output, so I don't see my rendered HTML.
Component
componentDidMount() {
/* Nothing here. The component should initially be empty. */
}
render() {
const { study, items } = this.props;
// THIS WORKS Another component triggers this one's state change, I get the alert
alert('State changed: ' + study);
if (study) {
/* Ajax call in render(). The fetch works as verified with console.log(result) */
fetch("/api/myCall?id=" + study)
.then(res => res.json())
.then(
(result) => {
return <div>RESULT OBTAINED</div> <-- THIS DOESN'T WORK, result is OK
},
(error) => {
return <div>ERROR</div>
}
);
} else {
return <div>EMPTY</div>
}
render(). Populate state after results are received by fetch and use state variable in render..then(...is asynchronous. Small wonder you don't see anything. You need to update a state variable with those results and let the component re-render to see anything.