Issue with rendering Base64 image array strings in FlatList component in React Native

In my RN App, I am trying to display a FlatList with Image Items but it seems like I have missed something. I am retrieving blob data from my API, converting it to a String using Buffer, and then adding it to an Array. This Array is used to populate the FlatList.

export function HomeScreen() {
  const imagesList: any = [];

  useEffect(() => {
    loadData();
  }, []);

  const loadData = async () =>{
    await callAPI().then(res => {
      //blob base64 is from type jpeg
      imagesList.push({imageURI: "data:image/jpeg;base64,"+Buffer.from(res.image1).toString('ascii')})
    })
  }

  return (
    <View style={[styles.imageSlider, {width, height}]}>
      <FlatList
        data={imagesList}
        renderItem={({item, index}) => (
          <>
            {console.log('item: ', item)}
            <Image
              key={index}
              source={{uri: item.imageURI}}
              style={{
                height,
                width,
                resizeMode: 'cover',
                maxHeight: 500,
                maxWidth: 500,
              }}
            />
          </>
        )}
      />
    </View>
  )
}

I have validated the data received from the api and everything appears to be correct, however, the images are not rendering. Could someone identify what might be causing this issue? I do not possess advanced knowledge in RN. Thank you!

Answer №1

There are a couple of issues that need attention...

  1. It appears that you are not utilizing any state in your code
  2. You seem to be encoding the buffer as ASCII instead of Base64
// Implementing state using the useState hook
const [ imagesList, setImagesList ] = useState<Array<{ imageURI: string }> >([]);

const loadData = async () => {
  const { image1 } = await callAPI()
  // You're expecting an array for some reason ¯\_(ツ)_/¯
  return [{
    imageURI: `data:image/jpeg;base64,${Buffer.from(image1).toString("base64")}`
  }]
}

useEffect(() => {
  loadData.then(setImagesList)
}, [])

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Sending information to a VueJS component

Hey there! I have a challenge in VueJS where I need to transfer Firebase Authentication user data (JSON) from the App.vue component to another component named Details.vue. The goal is to display the name of the logged-in user on Details.vue. In App.vue: ...

JQuery datepicker is functioning properly only after an alert when loaded with AJAX

Here's a puzzling question I have encountered. I implemented a field with a datepicker functionality. This field gets loaded into a div through an AJAX call. To sum it up, everything seems to be in working order.. But there's a strange issue. I ...

Steps to creating a custom text editor using React for generating blog content and storing it in a MongoDB database

I have a challenge of building a rich text editor for my web app, specifically for creating blog posts that will be saved in the database for user viewing. Initially, I planned to use a form with input fields where the title and content of the blog post w ...

Which specific page initiates the post request?

Seeking help with my post request that originates from a specific page on my website: reqdata = 'text=' + mytext; $.ajax({ type: "POST", url: "/request.php", data: reqdata, cache: false, success: function(html) { alert(html) } ...

Ways to retrieve information beyond the scope of the 'then' method

One issue I am facing involves a piece of code that is only accessible inside of the 'then' function. I need to access it outside of this block in order to utilize it in other parts of my program. $scope.model = {'first_name':'&ap ...

Ignore one specific file when importing all files in Angular 7

In my Angular 7 project, I am utilizing C3 and importing all the necessary files at the beginning of my .ts component file using a wildcard. import * as c3 from 'c3'; While this method works well overall, I encountered an issue where my CSS ove ...

Enhancing React Native View and other component properties using styled-components

Utilizing styled-components for styling in my React Native app using Typescript has been effective. I recently crafted a StyledComponent to style a View component, but encountered an error when attempting to extend the ViewProps: The type '{ children: ...

Using array map to create a centered table in a React web application

In my React project, I created a table using the array.map function. However, I'm facing an issue where the output of array.map is always aligned to the left, even before the table itself. I want to center the entire table. JSX: <div className=&qu ...

Create a new project using Firebase Functions along with a Node.js backend and a React.js frontend

In the process of developing my application, I have chosen to utilize node.js, express.js, and Firebase with firebase functions, all coded in TypeScript. For the client side framework, I am interested in incorporating react.js. Currently, I have set up nod ...

Typescript - Keeping a log of object keys along with their corresponding key type values

Imagine having the following scenario where you need to create an object with keys that are transformed versions of the original type's values: export type CCDTypes = { AuthorisationCaseEvent: AuthorisationCaseEvent, AuthorisationCaseField: Author ...

Error encountered while trying to install npm: Permission denied in the /.npm/_cacache

Every time I try to use the sudo npm install command, I encounter an error. usr6783@usr6783:~/albarakaMobil/client/mobile-branch$ sudo npm install [sudo] password for usr6783: npm WARN deprecated [email protected]: This project has been renamed to ...

The promise is unexpectedly fulfilled ahead of schedule without returning the expected value from an AXIOS call

My current challenge involves making a request to a service that rapidly generates multiple strings. The problem lies in returning a promise from this service, as I lack control over the string-generation process. It is crucial for me to return a promise ...

Scouring the web with Cheerio to extract various information from Twitter

Just starting out with Web Scraping, using Axios to fetch the URL and Cheerio to access the data. Trying to scrape my Twitter account for the number of followers by inspecting the element holding that info, but not getting any results. Attempting to exec ...

What is the best method for setting a session cookie securely while also using CSRF tokens?

In my express application, I am working on setting the session cookie to be secure. Here is the code snippet I have tried so far: app.use(express.cookieParser()); sessionOptions = definitions.REDIS; sessionOptions.ttl = definitions.session.expiration; app ...

passing data from the view to the controller

When I choose an option from the dropdown menu, the selected value is not being passed to the controller action method. Although the selected value is binding in Ajax, it is not binding in the controller action method. Check out our page <div class="ro ...

Creating an HTML element that can zoom, using dimensions specified in percentages but appearing as if they were specified in pixels

This question may seem simple, but I have been searching for an answer and haven't found one yet. Imagine we have an HTML element with dimensions specified in pixels: <div style="width:750px; height: 250px"></div> We can easily resize i ...

What is the best way to differentiate and analyze new AJAX output from previous data using div elements?

Embarking on a project to develop a high/low game using JavaScript, I encountered a perplexing issue where the displayed numbers seemed to be out of sync with the variables stored. This discrepancy left me scratching my head as I struggled to get them to a ...

What is the best way to execute an inline function two times in a row

I'm currently utilizing Gametime.js to create a real-time world chat feature. All messages are kept in a database for storage. Interestingly, PubNub, which is used by Gametime.js, seems to require messages to be sent twice for them to actually go th ...

Clearing FullCalendar events when the month button is pressed: A step-by-step guide

What is the best way to hide ONLY events on a calendar? I was considering deleting all events when the user clicks the "month" button. How can I achieve this functionality? $scope.uiConfig = { calendar: { height: 450, editable: false, ...

Using JSDoc to Include TypeScript Definitions

I've been attempting to utilize the ts-xor package, which provides a TypeScript definition: export declare type XOR<T, U> = (T | U) extends object ? (Without<T, U> & U) | (Without<U, T> & T) : T | U; This is how I'm imp ...