Long story short;
I get team id from an API. When I got my team ids I want to make a get-request to my server that has the query to get the base64 from the databases and then display it when I get the string.
Currently I'm using a function to get the image:
getLogo(teamid) {
axios.get('url' + teamid)
.then(res => return res.data);
}
So that is my function, and this is my Image-component.
<Image
source={{ uri: `data:image/png;base64,${this.getLogo(this.homeid)}`}}
style={{ height: 50, width: 50 }}
/>
Is this wrong? Should I approach this differently? I know that the base64 I get from my endpoint is correct, because I tried console.log the result and insert it in any image-element and it works.
Thanks in advance!
Your getLogo function is asynchronous, meaning that it isn't going to return the base64 string for the image directly - instead it just fires off the HTTP request and exits, and your then handler fulfils the response promise when the data comes in. Your best bet would then be to update something in the state for this component, and reference that in your view.
So your HTTP call would become something like:
getLogo() {
axios.get('url' + this.homeid)
.then(res => this.setState({logo: res.data}));
}
(note I've removed the parameter to pass in the teamid, as it seems you were using a set variable this.homeid on the component to drive this anyway)
And you can then move the logo rendering to it's own function:
renderLogo() {
let logoImage = null;
if (this.state.logo) {
logoImage = (
<Image
source={{ uri: `data:image/png;base64,${this.state.logo}`}}
style={{ height: 50, width: 50 }}
/>
);
}
return logoImage;
}
You can then reference {this.renderLogo} wherever you want the logo to be displayed within render - doing it this way means it'll not show anything as it'll return null until the HTTP call returns, at which point it'll update the state, trigger a re-render, and show the logo. You could also use a spinner or alternative view of some kind instead of null if you wanted to indicate that the logo was loading.
You would need to call getLogo at some point to kick off the HTTP request - it's a good idea in general not to be making additional requests for data inside the render loop anyway.
If this is part of an array of logos, and you need it to be called multiple times for different team ids (which may be why you accepted teamid as a parameter?), or indeed if you plan on adding any other complexity or logic to the logo, I'd strongly suggest moving it into it's own TeamLogo component, that can have the id passed as a prop, make the HTTP call in the component initialization, and renders the base64 image accordingly based on the state updating as above.
Hope that helps, any further questions just leave a comment!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With