skylisk
skylisk

Reputation: 15

with Flatlists renderItem in react native, if I use the value of Item as an index of an array, it is undefined

when accessing the item passed to _renderItem, I can use the value like so <Text>{item.item}</Text> and it prints 1, 2, but cannot use it as an index for an array like this <Text>{get(GLOBAL, ['products', 'item.item', 'title'], '')}</Text> where this returns an empty string.

import get from 'lodash.get';

~~~

_renderItem = (item) => {

    return (
        <View style={{ flex: 1 }}>
            <Text>{item.item}</Text>
            <Text>{get(GLOBAL, ['products', 'item.item', 'title'], '')}</Text>
        </View >
    )
};

render() {
    return (
        <View style={styles.list}>
            <FlatList
                data={[1,2]}
                renderItem={this._renderItem} />
        </View>
    )
}

<Text>{get(GLOBAL, ['products', 'item.item', 'title'], '')}</Text> this outputs '' but <Text>{get(GLOBAL, ['products', '1', 'title'], '')}</Text> outputs as expected.

how-come these respond differently and how could I use the value passed in item to _renderItem as the index of an array?

the reason for this is that the data passed to the FlatList corresponds to the index of the product that I want to fetch certain information from.

any help appreciated!

Upvotes: 1

Views: 128

Answers (2)

Christos Lytras
Christos Lytras

Reputation: 37298

You want to use the item value and instead of the object and property, you're passing a string as a parameter for concating the lodash.get object. Try to do it like this:

_renderItem = (item) => {
    return (
        <View style={{ flex: 1 }}>
            <Text>{item.item}</Text>
            <Text>{get(GLOBAL, ['products', item.item, 'title'], '')}</Text>
        </View >
    )
};

That will actually get GLOBAL['products'][1]['title'] when the item is 1 instead of GLOBAL['products']['item.item']['title'] that you're having now.

Upvotes: 1

Thanh Cao
Thanh Cao

Reputation: 161

Don't forget is: _renderItem = ({item}) not _renderItem = (item)

Upvotes: 0

Related Questions