React Native - base64 image

Viewed 72

I'm trying to display an image that's been recorded to base64. I can console log and confirm the image is working. But I am not quite sure how to display it from the API request.

I'm completely new to typescript & coding in general, so just trying to get a further understanding, been stuck on this little problem for a little while.

const graphClient = Client.initWithMiddleware(clientOptions);

export class GraphManager {
  static getPhoto = async () => {
    return await graphClient
        .api('/me/photo/$value')
        .get()
        // display image 
        .then(res => {
          const reader = new FileReader();
          reader.readAsDataURL(res);
          reader.onloadend = () => {
          // return base64 image
            return reader.result
          };
        })
  };

Then on my main component


    const userPhoto = GraphManager.getPhoto()
    const HomeComponent = () => {

    const userContext = React.useContext(UserContext);
    return (
      <View style={styles.container}>
        <ActivityIndicator
          color={Platform.OS === 'android' ? '#276b80' : undefined}
          animating={userContext.userLoading}
          size='large'
        />
        {userContext.userLoading ? null : (
        <Image style={{ width: 200, height: 200 }} source={{ uri:`${UserPhoto}`}}/>
        )}
      </View>
    );
  };

I am able to get the image to show, if I put the base64 data in another file and export it as a const. But that's as far as I've gotten. I am new to classes/methods.

1 Answers

The problem is that GraphManager.getPhoto() is async. Your component gets rerendered while the image has not been fully loaded. You must trigger a rerender after the async function returns its data. This could be done by using a state instead and by loading the data initially on component mount in a useEffect with an empty dependency array.


const HomeComponent = () => {
    const userContext = React.useContext(UserContext);

    const [image,setImage] = React.useState();

    React.useEffect(() => {
       const load = async () => {
           const i = await GraphManager.getPhoto()
           setImage(i)
       }
       load()
    }, [])
    return (
      <View style={styles.container}>
        <ActivityIndicator
          color={Platform.OS === 'android' ? '#276b80' : undefined}
          animating={userContext.userLoading}
          size='large'
        />
        {userContext.userLoading || !image ? null : (
        <Image style={{ width: 200, height: 200 }} source={{ uri:`${image}`}}/>
        )}
      </View>
    );
  };
Related