rfii
rfii

Reputation: 593

React Native Updating setState not happening even after delay

I am stumped on the below bug or my lack of understanding about why my update to setState is not working. I read several questions saying setState isn't instant so I inserted some delays but it doesn't seem to change matter. Why is my setState call at the end not working?

import React, { Component } from 'react';
import { View, Text, FlatList, TextInput, ListItem } from 'react-native';

class SearchFunction extends Component {
  constructor(props) {
    super(props);
    
    this.state = {  
      data: [],
      value: '',
    };

    this.arrayNew = [
      { name: 'Robert' },
      { name: 'Bryan' },
      { name: 'Vicente' },
      { name: 'Tristan' },
      { name: 'Marie' },
    ];
    
    setTimeout(1000);
    this.setState({data: this.arrayNew}, console.log(this.state));
    setTimeout(1000);
    console.log(this.state)
  }

The above console logs show that data is still []. Whereas I expected it to be this.arrayNew

Upvotes: 0

Views: 63

Answers (1)

jnpdx
jnpdx

Reputation: 52347

  1. setTimeout takes two parameters: a callback and a time interval. Calling setTimeout(1000) doesn't do anything

  2. this.setState shouldn't be called in the constructor -- your state inside the constructor should be set by this.state = like you have above

  3. Your syntax for this.setState isn't correct -- the first parameter is correct (the state object), but the second parameter should be a callback function (see my example)

Let's look at an example of a working function with some different places that print the state:

class SearchFunction extends React.Component {
  constructor(props) {
    super(props);
    
    this.state = {  
      data: [],
      value: '',
    };

    console.log("Initial state:")
    console.log(this.state)

    this.arrayNew = [
      { name: 'Robert' },
      { name: 'Bryan' },
      { name: 'Vicente' },
      { name: 'Tristan' },
      { name: 'Marie' },
    ];
    
    setTimeout(() => { 
      this.setState({data: this.arrayNew}, () => {
        console.log("Newly set state:")
        console.log(this.state)
      });
    }, 1000);
  }

  render() {
    return <View/>;
  }
}

Snack example: https://snack.expo.io/4kVsJHJ0d

  1. After the initial this.state = you can see the state is empty
  2. setTimeout with a callback function and an interval of 1 second
  3. In the callback function, the state is set with the correct syntax of this.setState with an arrow function as the callback. You can see that after it runs, it calls its own callback function, which prints the updated state.

Upvotes: 2

Related Questions