-1

I'm reasonably new to RN and having what will prob be a basic issue with setting state - Currently I have the following - various tasks run in the constructor but the setState tasks dont work - Ive tried the same function in componentdidmount and get the same issue - can anyone please explain where i'm going wrong?

import React from 'react';
import { connect } from "react-redux";
import {View, Image, StyleSheet, Text, StatusBar, TouchableOpacity, ScrollView} from 'react-native';
import CopyrightSpiel from './util/CopyrightSpiel';
import ButtonHomeNav from './util/ButtonHomeNav';
import BlinkMe from './util/BlinkMe';
import PropTypes from 'prop-types';
import moment from 'moment';

import { withNavigation } from 'react-navigation';

class HomeView extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      loggedIn:false,
      expDateClose :false,
      expDays : 0,

    };

    console.warn('daysRem');
    let curDate= new Date();
    let expDate= new Date(this.props.user.badgeExpiry);
    if (!moment.isMoment(curDate)) {curDate = moment(curDate);}
    if (!moment.isMoment(expDate)) {expDate = moment(expDate);}
    const daysRem = expDate.diff(curDate, 'days');
    console.warn(daysRem);
    if(daysRem >= 600){
      console.warn(daysRem);
      this.setState({expDays: 15});

      console.warn(this.state.expDays);
      console.warn(this.state.expDateClose);
    }

  }





render() {
Dancer
  • 17,035
  • 38
  • 129
  • 206
  • Possible duplicate of [setState doesn't update the state immediately](https://stackoverflow.com/questions/41278385/setstate-doesnt-update-the-state-immediately) – JJJ Apr 01 '19 at 12:00
  • 2
    Also note that using `setState` in the constructor is not necessary – just set the state directly (`this.state.expDays = 15`) – JJJ Apr 01 '19 at 12:01

2 Answers2

3

You have to keep in mind that setState is an asynchronous function and will not have set the state right after its return. Your state get changed, but after you "console.warn" it out.

You can pass a callback as the second parameter to proceed.

this.setState({expDay: 15}, () => {console.warn(this.sate)})

https://reactjs.org/docs/react-component.html#setstate

1

React.setState is not syncrhonous, it enqueues changes to the component state and tells React that this component and its children need to be re-rendered with the updated state.

https://reactjs.org/docs/react-component.html#setstate

jgoday
  • 2,768
  • 1
  • 18
  • 17