Search code examples
react-nativereact-native-router-flux

React Native Pass data to another screen


I need to pass some data from one screen to another, but I don't know how to do it. I've searched and I read about Redux, but it is a bit complicated since I never used it and most of the tutorials are confusing for a newcomer. But if I could do it without Redux, that would be better.

So, when I click in a button, It runs this:

  onSearch() {
    var listaCarros = fetch(`URL`, {
        method: 'GET',
        })
      .then((response) => { return response.json() } )
      .then((responseJson) => {
        console.log(responseJson)
      })
  }

and I want to pass the data I get from this, to another screen. Im using router-flux, if that matters.


Solution

  • you can save the response in state of your current component like

    onSearch() {
        var listaCarros = fetch(`URL`, {
            method: 'GET',
            })
          .then((response) => { return response.json() } )
          .then((responseJson) => {
            console.log(responseJson);
            /*for react-native-router-flux you can simply do
             Actions.secondPage({data:responseJson});  and you will get data at SecondPage in props
    
           */
            this.setState({
             dataToPass :responseJson
            });
          })
    }
    

    then below in return like you want to pass data to a new component having named as SecondPage, you can do it in following way

    render(){
      return(
       {this.state.dataToPass && <SecondPage data ={this.state.dataToPass}>} //you will get data as props in your second page
      );
    }