React-Native setState not updating during fetch()


#1

I have 3 records in my table, I can see the app fetches record to my remote because I console.log the response. My problem is that it will not display the item.

I know I defined correctly the column in FlatList because If I will set the per_page=1 which means pull 1 record every request. It will display but 2 records only will display the last record will not, if I set to per_page=30 nothing displays. is there a problem in my setState() during the response ?.I heard that setSate is not mutable..how can I apply the updater function of setsate in my code.?...I am still fresh on react native I hope someone will help me here.

I tried to do this but no luck!..also is this will matter that I use react-redux in my other page then in this screen I did not use only handling of state. ?...please help me react-native experts.

this.setState({
                        page: this.getParameterByName('page', res.next_page_url),
                        data: this.state.page === 1 ? res.data : [...this.state.data, ...res.data],
                        error: res.error || null,
                        loading: false,
                        refreshing: false,
                        last_page: res.last_page
                    },()=>{
                       return this.state;
                   });

Here is my complete code

import React, { Component } from 'react';
import {ScrollView, Text, View, Button, FlatList, ActivityIndicator} from 'react-native';
import { List, ListItem, Icon } from "react-native-elements";
import {connect} from "react-redux";
import numeral from "numeral";
import Moment from 'react-moment';
import moment from 'moment';

class Screen1 extends Component {
    constructor(props) {
        super(props);

        this.state = {
            loading: false,
            data: [],
            page: 1,
            per_page: 30,
            order_by:'id',
            sort_by:'asc',
            error: null,
            refreshing: false,
            param:'',
            last_page:''
        };
    }

    componentDidMount() {
        this.makeRemoteRequest();
    }

    makeRemoteRequest = () => {

        const {page, per_page,order_by,sort_by } = this.state;
        const url = `http://myapp.com/api/mobile/credit?page=${page}&api_token=${this.props.token}&per_page=${per_page}&order_by=${order_by}&sort_by=${sort_by}`;
        console.log("the url",url);

        this.setState({ loading: true });
        setTimeout(()=>{
            fetch(url)
                .then(res => res.json())
                .then(res => {
                   console.log("the page is =",this.getParameterByName('page',res.next_page_url));
                    this.setState({
                        page:this.getParameterByName('page',res.next_page_url),
                        data: this.state.page === 1 ? res.data : [...this.state.data,...res.data],
                        error: res.error || null,
                        loading: false,
                        refreshing: false,
                        last_page: res.last_page
                    });

                })
                .catch(error => {
                    this.setState({ error, loading: false });
                });
        },1500);
    };

    handleRefresh = () => {

        if( this.state.page) {
            if (this.state.page <= this.state.last_page) {
                this.setState(
                    {
                        refreshing: true,
                        page: this.state.page
                    },
                    () => {

                        this.makeRemoteRequest();


                    }
                );
            }
        }

    };

    getParameterByName = (name,url) =>{
        if (!url) url = window.location.href;
        name = name.replace(/[\[\]]/g, "\\$&");
        let regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
            results = regex.exec(url);
        if (!results) return null;
        if (!results[2]) return '';
        return  parseInt(decodeURIComponent(results[2].replace(/\+/g, " ")), 10);
    };
    handleLoadMore = () => {

        if( this.state.page){
            if( this.state.page <= this.state.last_page ){
                this.setState(
                    {

                        page: this.state.page
                    },
                    () => {
                        this.makeRemoteRequest();
                    }
                );

            }else{
                console.log("cannot handle more",this.state.page)
            }
        }else{
            console.log("page is null");
        }

    };

    renderSeparator = () => {
        return (
            <View
                style={{
                    height: 1,
                    width: "86%",
                    backgroundColor: "#CED0CE",
                    marginLeft: "14%"
                }}
            />
        );
    };

    renderHeader = () => {
        return (
            <View >
                <Text h1
                      style={{
                          color: 'blue',
                          fontWeight: 'bold',
                          textAlign: 'center',
                          fontSize: 30,
                          backgroundColor: "#CED0CE",

                      }}
                >{ numeral(this.props.thetotalcredit).format("#,##0.00") }</Text>
            </View>
        );
    };

    renderFooter = () => {
        if (!this.state.loading) return null;

        return (
            <View
                style={{
                    paddingVertical: 20,
                    borderTopWidth: 1,
                    borderColor: "#CED0CE"
                }}
            >
                <ActivityIndicator animating size="large" />
            </View>
        );
    };

    render() {

        return (


                <FlatList

                    data={this.state.data}
                    keyExtractor = {(item, index) => index.toString()}
                    renderItem={({ item }) => (
                        <ListItem

                            title= { numeral(item.amountcredit).format("#,##0.00") }
                            subtitle= { moment(item.creditdate).format("MMM DD, YYYY") }

                            containerStyle={{ borderBottomWidth: 0 }}
                        />
                    )}

                    extraData={this.state.data}
                    ItemSeparatorComponent={this.renderSeparator}
                    ListHeaderComponent={this.renderHeader}
                    ListFooterComponent={this.renderFooter}
                    refreshing={this.state.refreshing}
                    onRefresh={this.handleRefresh}
                    onEndReached={this.handleLoadMore}
                    onEndReachedThreshold={0.5}
                    stickyHeaderIndices={[0]}
                />

        );
    }
    }

    const mapStateToProps = (state) => {
    
        return {
    
            username: state.auth.username,
            token:state.auth.token,
            thetotalcredit:state.auth.total_credit
    
    
    
        };
    };
    
    export default connect(mapStateToProps)(Screen1);

#2

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.