I am trying to to an asynchronous fetch call once my modal is opened. I need that call because It fetched images and it will take around 5 seconds for the fetch to get a response.
So the modal should show first with the data and then once the fetch is complete, it should show the fetch data also.
My problem is that at the moment when calling the function with this () => {this.fetchImages(id) it is not called. I assume it's because the function is being assigned and not called.
But when I call the function fetchImages() without the () =>, I get this error :
Invariant Violation: Minified React error #31
This is my code, irrelevant part has been removed for simplicity:
renderModal = () => {
...
return (
<Modal open={openModal != null} onClose={this.closeModal}
little showCloseIcon={true} styles={modalStyles}>
<div className="item">
...
{() => {this.fetchImages(id)
.then(r => console.log("Fetch result" + r))}}
</div>
</Modal>
);
}
fetchImages = async (id) =>{
console.log("Request started")
try{
let myImages = null;
if(typeof(id) !== 'undefined' && id != null) {
myImages = await fetchImages(id);
console.log("Images: " + myImages);
return (
<div>
{Array.isArray(myImages) && myImages.length !== 0 && myImages.map((item, key) =>
<p>Image name: {item.name}, En device name: {item.name.en_US}</p>
)}
</div>
);
}
} catch (e) {
console.log("Failed")
}
}
EDIT
By changing the code as suggested by jack.benson and GalAbra, I ran into an issue where I am stuck in an endless loop. I will add the new code:
Once the page loads up the renderModal is called in render() method:
{this.renderModal()}
Then I have a button that would show the modal since modal contains a line :
<Modal open={openModal != null} onClose={this.closeModal}
little showCloseIcon={true} styles={modalStyles}>
It is called from here:
myMethod = (task) => {
...
return (
<div {...attrs}>
...
<button onClick={() => {this.showModal(documents[0])}}>{translate('show_more')} »</button>
</div>
}
</div>
</div>
);};
And the part to show the modal:
showModal = (document) => {
this.setState({ modalOpen: document });
};
And now the new renderModal():
renderModal = () => {
const doThing = async () => {
try {
const newImages = await downloadDeviceImages(id);
return { data: newImages };
} catch (e) {
console.log("Failed")
}
};
const test = async (id) => {
const imageData = await doThing(id);
console.log("after", imageData.data);
this.setState({
imageData: imageData.data
});
};
if(typeof(id) !== 'undefined' && id != null) {test(id);}
return (
<Modal open={openModal != null} onClose={this.closeModal}
little showCloseIcon={true} styles={modalStyles}>
<div className="item">
...
<div>
{this.state.imageData.map((item, key) =>
<p>Device name: {item.name}, En device name: {item.name.en_US}</p>
)}
</div>
</Modal>
);
}
The main part here is that the button will be clicked multiple times and it might have different ID on every click so a new request should be made every time.