Take data from an React Native array

Asked

Viewed 753 times

-1

I need to get data from a array of the server to display to the user. A is a show as if it were a feed of a social network, but is showing the same contents over and over again.

componentDidMount = async () => {
    await api.get('postagens').then(res=>{
        this.setState({id_postagens: res.data.count});
        this.setState({posts: res.data.posts});
    });
    for(let i = 0; i<=this.state.id_postagens; i++){
        const {titulo, criador} = this.state.posts[i];
        this.setState({titulo,criador});
    }
};

render() {
    var valor = this.state.id_postagens;
    var i=0;
    var postagens = [];
      

    while(i<valor){
        const {criador, titulo} = this.state;
        postagens.push(<View styles={{flex:1}} key= {i}>
        <View style={styles.box}>
          <View
            style={styles.foto}>
          </View>
        <Text  style={styles.texto}>{criador}</Text>
            <Text  style={styles.tempo}>30 min.</Text>
          <View>
          <Text style={styles.titulo}>{titulo}</Text>
          </View>
            <TouchableOpacity style={styles.iconComment}>
              <Icon name="message-circle" size={25} color="#31788A" />
              <Text style={styles.message}>0</Text>
            </TouchableOpacity>
        </View>
        </View>)
        i++;
    }
    return (
        <ScrollView>
            <View>
                {postagens}
            </View>
        </ScrollView>
    )
}
  • if code is not usual in the world React, an example is to use while really very different, I’m not saying it can’t work, but it’s different than what we see around. In the function where you placed the request and then the status update of several variables does not give time to later execute a for ... there’s something strange about your code and that’s why, could improve understanding with an issue?

  • Try to put this counter out of render, because React renders the page several times and I think that at each rendering it is initiating the variable

1 answer

0

First, the ideal would be for you to create a function async outside the componentDidMount. With the function created outside, you simply call it in componentDidMount leaving him normal, without being async.

That said, let’s get back to your initial problem. Usually in React when you want to show an array of information on the screen, you simply do a map in it. In your example, you want to limit the number of rendered items, this can be done using the method slice, so you take only the part of the array you need and apply the map in the same. It is worth mentioning that you can give a setState with more than one variable and setState within a loop is not something desirable, and can harm the performance of your application.

I believe the ideal in your situation would be to dismiss the for under the requisition and perform a slice along with a map in the variable this.state.posts. It would look something like this:

  getPostagens = async () => {
    await api.get("postagens").then(({ data }) => {
      this.setState({ id_postagens: data.count, posts: data.posts });
    });
  };

  componentDidMount() {
    getPostagens();
  }

  render() {
    return (
      <ScrollView>
        <View>
          {this.state.posts
            .slice(0, this.state.id_postagens)
            .map(({ criador, titulo }, index) => (
              <View styles={{ flex: 1 }} key={index.toString()}>
                  {...}
              </View>
            ))}
        </View>
      </ScrollView>
    );
  }

The ideal would also be to validate whether the this.state.posts is empty to avoid errors. I recommend you take a look at the component FlatList, she handles this kind of task better and would be more recommended in your case.

  • I tried this way but is giving the error: "Undefined is not an Object (evaluating 'this.state.posts.Slice')"

Browser other questions tagged

You are not signed in. Login or sign up in order to post.