Add List to Picker.Item component from JSON data react native expo

357 Views Asked by At

I want to add data to the <Picker.Item> component of the JSON that I pulled from AsyncStorage. but the result is an error the following code that I made:

constructor(props) {
      super(props);    
      this.state = {
         url: '',
         
      }
      this.checkurl();      
    }



checkurl = async () => {    
    
    const urlget = await AsyncStorage.getItem('url');        
    if(urlget) {        
      this.setState({ url: urlget });
    } else {
      console.log('data url empty');
    }
  }


render () {
    const urlListrender = this.state.url.map((item) =>
    <Picker.Item label={item.alias} value={item.url} key={item.id}/>
    );

    return(

        <View>
          <Picker 
              style={styles.pickerText}
              selectedValue={this.state.url}
              onValueChange={(itemValue,itemIndex) => this.setState({url: itemValue})}>              
              {urlListrender}
          </Picker>
       </View>

        )   
}

what mistake have I made? how do i fix it?

2

There are 2 best solutions below

5
On

try the following. I made changes to a few things.

constructor(props) {
      super(props);    
      this.state = {
         url: [],
         
      }
    }

componentDidMount(){
  this.checkurl();      
}

checkurl = async () => {    
    
    const urlget = await AsyncStorage.getItem('url');        
    if(urlget) {        
      this.setState({ url: urlget });
    } else {
      console.log('data url empty');
    }
  }


render () {
   if (this.state.url === undefined || this.state.url === null) return null;

   const urlListrender = this.state.url.map((item) =>
    <Picker.Item label={item.alias} value={item.url} key={item.id}/>
    );

    return(

        <View>
          <Picker 
              style={styles.pickerText}
              selectedValue={this.state.url}
              onValueChange={(itemValue,itemIndex) => this.setState({url: itemValue})}>              
              {urlListrender}
          </Picker>
       </View>

        )   
}
0
On

Maybe you haven't figured out the data types and usages that AsyncStorage can store at all. I suggest you read the official documents in detail.

Of course, there is also an open source library that can help you access the data in AsyncStorage more conveniently. It will help with data storage, retrieval, and type conversion. You can access any data in AsyncStorage like memory objects.

react-native-easy-app