Image Source In Async Function?
Solution 1:
Why it does not work
asd() is an async function. That means, it will return a promise, NOT the value (your base64 string). Read more about that here.
How it can be solved
Well, you could just do ${await this.asd()}
. Because you are using await, you'd have to make render() async. But that is not possible in react. Besides, you'd be refetching the data on every component rerender.
A better approach would be to put the data in the state of your component:
// You can supply a default value as argument to useState()const [avatarSrc, setAvatarSrc] = React.useState("");
// To retrieve the value:<Avatarsource={{uri:avatarSrc,
}}
/>
Then you can fetch your data with the useEffect hook:
React.useEffect(() => {
asd()
.then((data) =>setAvatarSrc(`data:image/png;base64,${data}`))
}, []);
Note the empty array as second parameter. This prevents from refetching on every new render, see https://css-tricks.com/run-useeffect-only-once/.
Solution 2:
If you call this.asd()
you will just render [object Promise]
because asd
is an async function, which returns a promise.
You need to load the photo in useEffect(() => { /* loado the photo */}, [])
exportdefaultfunctionAppointments({ data }) {
const [uri, setUri] = React.useState('')
React.useEffect(() => {
const asd = async () => {
const user = data.item.userLogin.toLowerCase();
const response = await axios.get(
`https://api4.successfactors.com/odata/v2/Photo?$filter=tolower(userId) eq '${user}'`,
{
auth: {
username: 'Apiuser',
password: 'Apipass',
},
}
);
const encodedData = response.data.d.results[0].photo.toString();
console.log(encodedData);
setUri(encodedData);
};
asd()
}, [])
return (
...
<Avatar
source={{
uri: `data:image/png;base64,${uri}`,
}}
/>
)
}
Post a Comment for "Image Source In Async Function?"