0

I am using a flat list and have some items using fetch API, but when I send item according to the id on another page it wont show anything. On another page I am fetching JSON data according to the id. That data it is not showing. And when I create local JSON it renders the single item as well but not when I use the fetched JSON. Here is my code i have a button Details in renderItem function, when i click on it am going on description page where i am getting json using fetch in component did mount. but according to the id it is not rendering coz i need a particular product description.

 constructor(props) {
    console.log('constructer called');
    super(props)

    this.AddToCart = this.AddToCart.bind(this);
    this.renderItem = this.renderItem.bind(this);

    this.state =
        {
            showToast: false,
            qty:0,
            dataSource: [],                
            opacity: new Animated.Value(0)

        }
}




 renderItem = ({ item }) => {


    console.log('all the items from SliderProductPage  ' + item.name + ' is  ' + JSON.stringify(item.category_id));

    return (

        <View style={{ flex: 1, flexDirection: 'column', }}>


            <View style={{

                justifyContent: 'center',
                alignItems: 'center',
                borderBottomWidth: responsiveHeight(0.2),
                marginHorizontal: responsiveHeight(5),
                borderBottomColor: 'tomato',
                //backgroundColor: this.props.index % 2 == 0 ? 'mediumseagreen': 'tomato'                
                //backgroundColor: 'tomato'
            }}>

                <Animated.Image
                    onLoad={this.onLoad}
                    {...this.props}
                    source={{ uri: item.item_url }}
                    style={{
                        opacity: this.state.opacity,
                        transform: [
                            {
                                scale: this.state.opacity.interpolate({
                                    inputRange: [0, 2],
                                    outputRange: [0.85, 1]


                                })
                            }],
                        width: responsiveHeight(40),
                        height: responsiveHeight(35),
                        justifyContent: 'center',
                        marginTop: responsiveHeight(3),
                        alignItems: 'center'

                    }}
                >

                </Animated.Image>


                <View style={{justifyContent:'center', alignItems: 'center', marginBottom:responsiveHeight(2), }}>
                     <Text style={{ fontSize: responsiveFontSize(1.6), color: 'red', }}> {item.name} </Text>
                    <Text style={{ fontSize: responsiveFontSize(1.6), color: 'red', }}> $ {item.price} </Text>
                    <Text style={{ fontSize: responsiveFontSize(1.6), color: '#000000', marginHorizontal: responsiveHeight(2) }}>{item.description} </Text>
                </View>


                <View style={{

                    marginBottom: responsiveHeight(1.5),
                    flexDirection: 'row',
                    alignItems: 'center',

                }}>

                    <TouchableNativeFeedback activeOpacity={.5} onPress={() => this.props.navigation.navigate('ProductDescription', { id: item.id }, console.log("ProductDetails-SliderProductPage sending id-------" + JSON.stringify(item.id)))}
                        background={Platform.OS === 'android' ? TouchableNativeFeedback.SelectableBackground() : ''}>
                        <View style={styles.button}>
                            <Text style={styles.buttonText}>Details</Text>
                        </View>
                    </TouchableNativeFeedback>

                    <TextInput 
                    onChangeText={(update)=> this.setState({qty:update})}
                    keyboardType="numeric"  placeholder="0" placeholderTextColor="red"  underlineColorAndroid="transparent"
                    style={{padding:0,
                        borderWidth:0.5,
                        borderColor:'green',
                        height:responsiveHeight(4),
                        width:responsiveWidth(10),
                        color:'red',
                        //alignContent:'center'
                        textAlign:'center'
                    }} >

                        {this.state.quantity}
                    </TextInput>


                    <TouchableNativeFeedback  onPress={this.AddToCart.bind(this,item)}
                        //()=>this.props.navigation.navigate('AddCartItems',{id:item.id,name:item.name},console.log("SliderProductPage sending id and name to ADD to cart page-------"+JSON.stringify(item.id+" and "+item.name),alert(item.name+ "  Added ")))} 
                        background={Platform.OS === 'android' ? TouchableNativeFeedback.SelectableBackground() : ''}>
                        <View style={styles.button}>
                            <Text  style={styles.buttonText}>Add</Text>

                        </View>
                    </TouchableNativeFeedback>

                </View>
            </View>
            <View style={{
                height: 1,

                backgroundColor: 'white'

            }}>

            </View>


        </View>




    )
}



 componentDidMount() {
    console.log("we are on slider page componentDidMount function")
    const { navigation } = this.props;
    const id = navigation.getParam('id', 'NOT A ID');
    const name = navigation.getParam('name', 'not a valid name')
    console.log("here is id fetch data" + JSON.stringify(id) + ":::::::::SliderPage::::::::::" + JSON.stringify(name))

    const url = 'http://192.168.0.105:8081/products/get/alldata/item?category_id=' + id;

    fetch(url)
        .then((response) => response.json())
        .then((responseJson) => {
            this.setState({
                dataSource: responseJson.Category,


            }, console.log("**************helo it is response sliderPage data********************" + JSON.stringify(responseJson.Category)))

        })
        .catch((error) => {
            console.log(error);
        })
}


   render() {

    var textValue = this.state;
    console.log("we are on slider page  render Function")

    const { navigate } = this.props.navigation;
    const { navigation } = this.props;
    const id = navigation.getParam('id', 'not an valid id');
    const name = navigation.getParam('name', 'not a valid name')
    console.log(id);

    return (
        <View>

            <FlatList
                extraData={this.state}
                data={this.state.dataSource}
                renderItem={this.renderItem}
                keyExtractor={item => item.name}
                keyboardShouldPersistTaps="always"
                onEndThreshold={0}
            />


        </View>


    )
}

};

Product_Description logic Page-:

constructor(props) {
    console.log('constructer called');
    super(props)

    this.state = {

        dataSource: [],
        opacity: new Animated.Value(0)
    }
}

onLoad = () => {
    Animated.timing(this.state.opacity, {
        toValue: 1,
        duration: 500,
        useNativeDriver: true,
    }).start();
}

static navigationOptions = {

}


componentDidMount() {
    console.log("we are on Product_Description_Logic page componentDidMount function")
    const { navigation } = this.props;
    const id = navigation.getParam('id', 'NOT A id');

    console.log("here is name fetch data" + JSON.stringify(id))

    const url = 'http://192.168.0.105:8081/products/get/item_desc?item_id=' + id;

    fetch(url)
        .then((response) => response.json())
        .then((responseJson) => {
            this.setState({
                dataSource: responseJson.item_desc,


            }, console.log(responseJson.item_desc))
        })
        .catch((error) => {
            console.log(error);
        })
}
renderItem = ({ item,index }) => {
    console.log("-----------------------render item data Product_Description_Logic is---------------:: " + JSON.stringify(item))
    return (



        <View style={{ flexDirection: 'column', }}>

            <View style={{
                flex: 1,
                //height: responsiveHeight(50),
                //width: responsiveWidth(100),
                alignItems: 'center',

            }}>

                <Animated.Image
                    onLoad={this.onLoad}
                    {...this.props}
                    source={{ uri: item.item_url }}
                    style={{
                        opacity: this.state.opacity,
                        transform: [
                            {
                                scale: this.state.opacity.interpolate({
                                    inputRange: [0, 2],
                                    outputRange: [0.85, 1]
                                })
                            }],
                        width: responsiveHeight(35),
                        flex: 1,
                        height: responsiveHeight(25),
                        marginTop: responsiveHeight(3),
                        alignItems: 'center'
                    }}>

                </Animated.Image>
            </View>


            <View style={{ flex: 1 }}>


                <View style={{ flexDirection: 'row' }}>

                    <Text style={{ fontSize: responsiveFontSize(1.6), color: 'black', }}> Price : {item.price} </Text>


                    <TouchableWithoutFeedback>
                        <View style={{
                            alignItems: "center",
                            justifyContent:'center',
                            padding: responsiveHeight(0.5),

                            backgroundColor: '#ffab40',
                            marginHorizontal: responsiveHeight(8),
                            height: responsiveHeight(4.5),
                            width: responsiveWidth(30),
                            borderRadius: responsiveHeight(1)

                        }}>
                            <Text style={{ color: '#000000', fontSize: responsiveFontSize(1.8), justifyContent: 'flex-end', }}>Add to Cart</Text>
                        </View>
                    </TouchableWithoutFeedback>


                </View>




                <Text style={{
                    fontSize: responsiveFontSize(2),
                    color: '#000000',
                    //marginHorizontal: responsiveHeight(1)
                }}>{this.state.description}</Text>
                <Text style={{ fontSize: responsiveFontSize(1.7), color: '#000000', }}> available:  {item.available} </Text>


            </View>




            <View style={{ margin: responsiveHeight(1), }} >
                <Text style={{ fontSize: responsiveFontSize(2), color: 'green', }}>{item.available} </Text>
                <Text style={{ fontSize: responsiveFontSize(2), color: '#000000', }}>Quantity: 5 </Text>

            </View>


            <Text style={{ fontSize: responsiveFontSize(2), color: '#000000', margin: responsiveHeight(1) }}>About this item </Text>

            <View style={{ borderWidth: responsiveHeight(0.1), margin: responsiveHeight(2), borderColor: 'gray' }}>
                <Text style={{ fontWeight: 'bold', color: '#000000', fontSize: responsiveHeight(2) }}>  Features and details: </Text>
                <Text style={{ fontSize: responsiveHeight(2), color: '#000000', marginHorizontal: responsiveHeight(1) }}> Graded, sorted and premium quality fruits </Text>
                <Text style={{ fontWeight: 'bold', color: '#000000', fontSize: responsiveHeight(2) }}> Product Details: </Text>

                <View style={{ flexDirection: 'row' }}>
                    <Text style={{ fontSize: responsiveHeight(2), color: '#000000', marginHorizontal: responsiveHeight(1), fontWeight: 'bold' }}> Manufacturer:</Text>
                    <Text style={{ fontSize: responsiveHeight(2), color: '#000000', marginHorizontal: responsiveHeight(1), }}>Fresh</Text>


                </View>
                <View style={{ flexDirection: 'row' }}>
                    <Text style={{ fontSize: responsiveHeight(2), color: '#000000', marginHorizontal: responsiveHeight(1), fontWeight: 'bold' }}> Item Part Number:</Text>
                    <Text style={{ fontSize: responsiveHeight(2), color: '#000000', marginHorizontal: responsiveHeight(1), }}>Apple_163</Text>
                </View>
                <View style={{ flexDirection: 'row' }}>
                    <Text style={{ fontSize: responsiveHeight(2), color: '#000000', marginHorizontal: responsiveHeight(1), fontWeight: 'bold' }}> ASIN:</Text>
                    <Text style={{ fontSize: responsiveHeight(2), color: '#000000', marginHorizontal: responsiveHeight(1), }}>vhajgdgvhjdjhd</Text>
                </View>

                <View style={{ borderBottomColor: 'gray', borderBottomWidth: responsiveHeight(0.1) }} />

                <Text style={{ fontWeight: 'bold', color: '#000000', fontSize: responsiveHeight(2), marginHorizontal: responsiveHeight(1) }}>Description: </Text>
                <Text style={{ color: '#000000', fontSize: responsiveHeight(1.8), marginHorizontal: responsiveHeight(1) }}>
                    {item.description}  </Text>

                <View style={{ borderBottomColor: 'gray' }} />
                <Text style={{ fontWeight: 'bold', color: '#000000', fontSize: responsiveHeight(2) }}> Important Information: </Text>

                <Text style={{ color: '#000000', fontSize: responsiveHeight(1.8), marginHorizontal: responsiveHeight(1) }}>
                    {item.imp_info}
                </Text>



                <TouchableWithoutFeedback>
                    <View style={{
                        alignItems: 'center',
                        padding: responsiveHeight(1),
                        backgroundColor: '#ffab40',
                        margin: responsiveHeight(5),
                        borderRadius: responsiveHeight(1)
                    }}>
                        <Text style={{ color: '#000000', fontSize: responsiveFontSize(1.8) }}>Continue Shopping</Text>
                    </View>
                </TouchableWithoutFeedback>



            </View>




        </View>




    );
}





render() {
    const { navigate } = this.props.navigation;
    const { navigation } = this.props;
    const id = navigation.getParam('id', 'not an valid id');

    console.log("this is prodcuctionDescription Render Fun" + JSON.stringify(id))


    return (

        <View>

            <FlatList
                data={this.state.dataSource}


                renderItem={this.renderItem}

                keyExtractor={item => item.name}

                onEndThreshold={0}


            />



        </View>




    )
}

};

7
  • Show us some code :) Commented Jun 14, 2018 at 7:22
  • And you could probably send the item instead of just its id to avoid to much fetching. But hard to give any advice before you show what you've tried so far Commented Jun 14, 2018 at 7:24
  • Formatting and typos Commented Jun 14, 2018 at 9:34
  • Hello Sir I updated my code please check and let me know because using flatlist having many issues, thanks in advance. Commented Jun 14, 2018 at 12:17
  • Have you tried defining a height/width or flex for your FlatList? Sometimes neglecting to add styling can cause FlatList to appear empty. Not sure if that's what you're experiencing, I only glanced at the code, but it's worth checking. :) Commented Jun 16, 2018 at 2:20

1 Answer 1

1

Had the same issue and got a fix for it from @ValdaXD Let me quote him word for word

It may not be flatlist, since it works with one item ... it may be the data

Some API's return an array of json for multiple data Ex: [{1...},{2...},{3...}] and that is well received by the faltlist component. But when requesting only one item , the apis return an individual json Ex: {1...} , and faltlist only accepts an array of json, not an individual json...

For that you can use a validator function that will check if the data is array, or an individual json , and call it before using it as the flatlist data. it would help if you placed the response from both an item group, or an individual item

formatJSON(data){
    var result = []
    if(!Array.isArray(data)){//if is not an array
        result.push(data) // push it as the first item of an array
    }else{
        result=data
    }

    return result
}

SO ADD THIS TO YOUR fetch

componentDidMount() { console.log("we are on Product_Description_Logic page componentDidMount function") const { navigation } = this.props; const id = navigation.getParam('id', 'NOT A id');

console.log("here is name fetch data" + JSON.stringify(id))

const url = 'http://192.168.0.105:8081/products/get/item_desc?item_id=' + id;

fetch(url)
    .then((response) => response.json())
    .then((responseJson) => {
        this.setState({
            dataSource: this.formatJSON(responseJson.item_desc),


        }, console.log(responseJson.item_desc))
    })
    .catch((error) => {
        console.log(error);
    })
 }

This trick worked for me

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.