how to use flatlist in react native with fetch api

Viewed 726

I am using react native with laravel back end so i just want to load list from laravel so for that i code like that

 constructor() {
    super();
    this.state = {
      data:[
        {
          student_name: '',
          class:'',
          section:'',
        }, 
      ],
    }
//id is also in state and i get it's value from async storage
fetch('http://192.1.1.:8000/api/students/' + this.state.id, {
    method: 'get',
  })
      .then((response) => response.json())
      .then((responseJson) => {  
        if (responseJson.message === 'success') {
          
            responseJson.data.map((userData) => {
            this.setState({student_name: userData.student_name})
            this.setState({class: userData.class})
            this.setState({section: userData.section})
        });
        } 

that's how i get record from laravel and update state in react native. but when i use flat list in react native it throw me that error

VirtualizedList: missing keys for items, make sure to specify a key or id property on each item or provide a custom keyExtractor.

My react native view is like that

<View>
  <Text style={{fontSize:50}}>FlatList</Text>
    <FlatList 
      data={this.state.data}
      renderItem={({item})=><Text style={{fontSize:50}}>{item.student_name}</Text>}
         />
</View>
4 Answers

Can you try this?

            keyExtractor={(item, index) => index.toString()}

You have to add a unique key (or id) prop for Text element in FlatList.

Supposing that your this.state.data items have an id, you could write something like:

<View>
  <Text style={{fontSize:50}}>FlatList</Text>
    <FlatList 
      data={this.state.data}
      renderItem={({item})=><Text key={item.id} style={{fontSize:50}}>{item.student_name}</Text>}
         />
</View> 

Alternatively, you could add keyExtractor to FlatList in this way:

<View>
      <Text style={{fontSize:50}}>FlatList</Text>
        <FlatList 
          data={this.state.data}
          renderItem={({item})=><Text style={{fontSize:50}}>{item.student_name}</Text>}
          keyExtractor={(item) => item.id}
             />
    </View> 

in Flatlist you have been need on key parameter . you must get that from list , like id parameter .
add this parameter to flatlist item

     style={styles.flatListStyle}
     data={this.state.bestSuggester}
     key={item => item.Rank}

Its because you are missing keyExtractor

Replace your code with this:

<View>
  <Text style={{fontSize:50}}>FlatList</Text>
    <FlatList 
      data={this.state.data}
      keyExtractor={(item, index) => String(index)}
      renderItem={({item})=><Text style={{fontSize:50}}>{item.student_name}</Text>}
   />
</View>
Related