Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React setState does not set state during a while loop

I want to avoid data multiplication, so i wanted to create a loop for calling my dataprovider for different site_id's.

I created a while loop and set the state values within this while loop. What I realized that from my 2 element array (I have 2 sites) only 1 is being set in the state, but the other one not.

class Dashboard extends Component {
state = {
    username: localStorage.getItem('username'),
    siteid: [{
        id: 1,
        daily: "EKdaily",
        weekly: "EKweekly",
        monthly: "EKmonthly",
        total: "EKtotal",
        },
    {
        id: 2,
        daily: "AKdaily",
        weekly: "AKweekly",
        monthly: "AKmonthly",
        total: "AKtotal",
    }]

};

componentDidMount() {
    dataProviderFactory('rest').then(
        dataProvider => {
            dataProvider(GET_ONE, 'users', {
                id: this.state.username,
            })
                .then(response => this.setState({ fullname: response.data.fullname }))

            dataProvider(GET_LIST, 'sites', {
                filter: { q: '' },
                sort: { field: '', order: '' },
                pagination: { page: 1, perPage: 1 },
            })
                .then(response => this.setState({ sites: response.data }))

            var i = 0;
            while ( i < 2 ) {
                var myId = this.state.siteid[i].id;
                var myDaily = this.state.siteid[i].daily;
                var myWeekly = this.state.siteid[i].weekly;
                var myMonthly = this.state.siteid[i].monthly;
                var myTotal = this.state.siteid[i].total;
                console.log("id", myId, myDaily, myWeekly, myMonthly, myTotal);
             dataProvider(GET_LIST, 'clicks', {
                filter: { interval: 'day', site_id: myId, count: '1', },
                sort: { field: 'date', order: 'DESC' },
                pagination: { page: 1, perPage: 50 },
            })
                .then(response => this.setState({ [myDaily]: response.data.count }))
            dataProvider(GET_LIST, 'clicks', {
                filter: { interval: 'week', site_id: myId, count: '1', },
                sort: { field: 'date', order: 'DESC' },
                pagination: { page: 1, perPage: 50 },
            })
                .then(response => this.setState({ [myWeekly]: response.data.count }))
            dataProvider(GET_LIST, 'clicks', {
                filter: { interval: 'month', site_id: myId, count: '1', },
                sort: { field: 'date', order: 'DESC' },
                pagination: { page: 1, perPage: 50 },
            })
                .then(response => this.setState({ [myMonthly]: response.data.count }))
            dataProvider(GET_LIST, 'clicks', {
                filter: { interval: 'all', site_id: myId, count: '1', },
                sort: { field: 'date', order: 'DESC' },
                pagination: { page: 1, perPage: 50 },
            })
                .then(response => this.setState({ [myTotal]: response.data.count }))
                i++;
            }
        }
    );
}

render() {
    const {
        fullname,
        username,
        EKdaily,
        EKweekly,
        EKmonthly,
        EKtotal,
        AKdaily,
        AKweekly,
        AKmonthly,
        AKtotal,
    } = this.state;
    const myPageHeader = `Udvozlunk az Admin feluleten ${fullname}!`;
    return (
        <div style={styles.flex}>
            <div style={styles.leftCol}>
                <div>
                    <Card>
                        <CardHeader title={myPageHeader} />
                        <CardContent>Bejelentkezett felhasznalo: {username}</CardContent>
                    </Card>
                </div>
                <div stlye={ { magrinTop: 200} }>
                    <Typography color="textPrimary">123.hu kattintas statisztikak</Typography>
                </div>
                <div style={styles.flex}>
                    <DisplayClick value={EKdaily} title="Napi Kattintas" />
                    <DisplayClick value={EKweekly} title="Heti Kattintas" />
                    <DisplayClick value={EKmonthly} title="Havi Kattintas" />
                    <DisplayClick value={EKtotal} title="Ossz Kattintas" />
                </div>
                 <div stlye={ { magrinTop: 20} }>
                    <Typography color="textPrimary">345.hu kattintas statisztikak</Typography>
                </div>
                <div style={styles.flex}>
                    <DisplayClick value={AKdaily} title="Napi Kattintas" />
                    <DisplayClick value={AKweekly} title="Heti Kattintas" />
                    <DisplayClick value={AKmonthly} title="Havi Kattintas" />
                    <DisplayClick value={AKtotal} title="Ossz Kattintas" />
                </div>
            </div>
        </div>
   );
}
}

Only AK* is being set in this.state, EK* not.

What do I do wrong?

like image 704
Reka Karolyi Avatar asked Mar 05 '19 04:03

Reka Karolyi


1 Answers

Use let instead of var here:

Change

var myId = this.state.siteid[i].id;
var myDaily = this.state.siteid[i].daily;
// ....

to

let myId = this.state.siteid[i].id;
let myDaily = this.state.siteid[i].daily;
// ....

var is scoped to the nearest function and not to the while block. It gets hoisted, and your code will be something like:

var i;
var myId;
var myDaily;

i = 0;

while ( i < 2 ) {
    myId = this.state.siteid[i].id;
    myDaily = this.state.siteid[i].daily;
}

Since dataProvider calls are asynchronous, the value of myId will be replaced with AK values by the first time call is done.

dataProvider(GET_LIST, 'clicks', {
    //
})
 .then(response => this.setState({ [myWeekly]: response.data.count }))
       /* ^^ This callback runs after the while block
           By this time, myDaily === "AKdaily" */
like image 80
adiga Avatar answered Sep 25 '22 04:09

adiga