Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React native -How to call async function inside a button when it is pressed?

Tags:

react-native

I am new to react native

I am trying to make a search page, the search bar in the top while the result will show up below it. I want my search button to call getsearchlist, the state 'data' will be set, and my search list will be rerendered. How to do it? When i try my code, nothing happen, and soon will show up Network request failed and 'Possible unhandled promise rejection'

    constructor(props) {
    super(props);
    this.state = {
        data: '',
        text: 'ducati'
    };
    this.getsearchlist = this.getsearchlist.bind(this);

}

async getsearchlist() {
    //console.log(this.state.text);
    let text = this.state.text;
    let response = await fetch('https://www.blabla.com');
    let responseXmlText = await response.text();
    let newsitem = JSON.parse(responseXmlText);
    let data = [];
    for (var i = 0; i < newsitem.length; i++) {
        var content = newsitem[i].content.rendered;
        var title = newsitem[i].title.rendered;
        var link = newsitem[i].link;


        var re = /<img[^>]+src="?([^"\s]+)"?[^>]*\/>/g;
        var results = re.exec(content);
        var imgsrc = '';
        if (results != null) {
            imgsrc = results[1];
        }
        data.push({
            title: title,
            content: content,
            img: imgsrc,
            link: link
        })
    }

    this.setState({
        data: data
    })

}

render() {
        var datas = this.state.data;

        return (
        <Container>
            <Header searchBar rounded>
                <InputGroup>
                    <Icon name='ios-search' />
                    <Input placeholder='Search'   onChangeText={(text) => this.setState({text})}
             value={this.state.text}/>
                    <Icon name='ios-people' />
                </InputGroup>
            </Header>


            <Content>
             <Button onPress={this.getsearchlist}>
                    Search
                </Button>
                 <List dataArray={datas}
                    renderRow={(data,sectionID, rowID) =>
                        <ListItem  >
                        <Thumbnail square size={100} source={{uri: data.img}} />

                            <Text style={[  styles.titlestyle]}>{data.title}</Text> 

                        </ListItem>
                    }>
                </List>
                    </Content>
        </Container>



        );
like image 733
smithenjelek Avatar asked Nov 14 '16 03:11

smithenjelek


1 Answers

Use something like this.

getSearchList = async () => {
  .....
  .....
}

And when you call it from the Button, call it just like you are calling it now.

<Button onPress={this.getSearchList} /> Search </Button>

Hope it helps :)

like image 169
Rishichandra Wawhal Avatar answered Sep 20 '22 15:09

Rishichandra Wawhal