Home > OS >  React Native: How to render fetch data in FlatList without id
React Native: How to render fetch data in FlatList without id

Time:06-26

I'm trying to render data from an API but it does not have an id or any unique data to distinguish the item

This is how the data looks like when I do console.log

Array [
  Object {
    "photo1": "www.picexample.com",
  },
  Object {
    "photo2": "www.picexample.com",
  },
]

This is my code:

Home.js

const [portfolio, setPortfolio] = React.useState([]);
const renderItem= ({item}) => {
    return (
        <View>
            <Image source={{uri: ?}} resizeMode="cover" />
        </View>
    );
}
useEffect (() => {
        .then((result) => {
            setPortfolio(result.myImage); 
            console.log(portfolio);
        })
});
return (
    <ScrollView>
        <FlatList
            scrollEnabled={false}
            data={portfolio}
            renderItem={renderItem} 
            keyExtractor={?}
        />
    </ScrollView>
);

UPDATE (Based on Joel Hager)

const keyExtractor = (portfolio, idx) => `${Object.keys(portfolio)}-${idx}`
const renderItem = ({item}) => {
    console.log(item);
    return (
        <View>
            <Image source={{uri: item}} resizeMode="cover" />
        </View>
    );
}
return (
    <FlatList
        scrollEnabled={false}
        data={portfolio}
        renderItem={renderItem} 
        keyExtractor={keyExtractor}
    />
);

CodePudding user response:

Without being able to post working React Native code, this will explain what it's doing conceptually.

It's taking the item instance in the array that's being passed (the 'item') It's grabbing all keys for it: Object.keys() It's displaying the first one

There are some caveats: It expects a value. You could always use null coalescence to do something else, but I'd have to know more about the data to cover those cases. If you always get a key, you'll always get a value. You can also add the index value in the extractor to give it some more specificity. Your react code should look like this:

keyExtractor={(item, idx) => `${Object.keys(item)}-${idx}`}

note: It's always good to extract the function outside of the flatlist so it isn't recreated every render. So it would look something like this:

const keyExtractor = (item, idx) => `${Object.keys(item)}-${idx}`
...
<Flatlist
...
keyExtractor={keyExractor}
...

More info on keyExtractor: https://reactnative.dev/docs/flatlist#keyextractor

The template literal will put the value of the string of the key and the index with a '-' between them. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

const payload = [
  {
    "photo1": "www.picexample.com",
  },
  {
    "photo2": "www.picexample.com",
  },
]

payload.map((item, idx) => console.log(Object.keys(item)[0]   `-${idx}`));

  • Related