I am trying to write my first React app and it is supposed to generate QR codes for different inputs and display them on a web page.
I already have my own 'library' function that does this thing for me - I only pass the data as a parameter and it returns a promise of data URL that I use as an src for an image and it's done. Here is how it works now:
class App extends Component {
constructor(props){
super(props);
this.state = {
dataUrl: '',
}
}
async componentDidMount(){
let url = await getDataURL('<some imaginary static data>');
this.setState({dataUrl: url});
}
render() {
return(
<div className="App">
<div>
<img alt="" src={this.state.dataUrl} style={{height: 200 + 'px', width: 200 + 'px'}} />
</div>
</div>
);
}
}
But now I need to call getDataURL() multiple times for some real data, e.g. I might have multiple <div>'s with different data and I need to get and render the QR code for each of them.
If I had a function, something like this:
async loadQRCode(data){
let url = await getDataURL(data);
return url;
}
Is there any way how to call it for each data directly from render() function? Or is there any better approach that I am missing?
render(). What you do is a) update yourstate(using as many async operations as you like) and b) render() the state. a) and b) happen independently, and since React re-renders whenever the state changes, all render() needs to do is render the current state; it doesn't have to worry about anything else. So if you have multiple QR codes, use an array for them in your state.loadQRCodewhich returns an image url and this is good to use it in a render.