Jack23
Jack23

Reputation: 1396

Using data from another class

I have a class in which I query to a DB some informations and I would to use these informations to display.

Class where I would to show data.

import React, { Component } from "react";
import FindUser from './FindUser';
let findUser = new FindUser();

class ShowProfile extends Component{
construct(props) {
super(props);
}
//...

render() {
    return (
      <View style={style.container}>
        <KeyboardAwareScrollView>
          <View style={style.page}>
            <Text style={visualProfilo.text}>Name:</Text>
            <Text style={visualProfilo.text1}>{this.state.FirstName}</Text>
            <Text style={visualProfilo.text}>Surname:</Text>
            <Text style={visualProfilo.text1}>{this.state.LastName}</Text>
//...
}

Class where I query the DB

class FindUser extends Component {
    constructor(props){
        super(props);
        this.state = {
        }
    }

    findUser(cf) {
        let params = {};
        params = {
          "Person.FiscalCode": cf
        };
        //... query to DB
          .then(response => {
            let utente = response.docs[0];
            console.log("name: ", user.Person.FirstName)

In this way I log the FirstName, than I would to use these informations to display as this.state.FirstName in ShowProfile. How can I do?

Upvotes: 0

Views: 587

Answers (2)

Lewa Bammy Stephen
Lewa Bammy Stephen

Reputation: 399

The very best approach to achieve what you is using React Native async storage, you save user information in it and retrieve into state using componentDidMount lifecycle method.

Here is an example

You may fetch user information from class A using this

   import {AsyncStorage} from 'react-native';

   GetUser = () => {
        return fetch( "http://sample.com/api/user/user.php", {
          method: "POST",
          headers:{
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            action: 'fetch'
          })
        }).then((response) => response.json()).then((responseJsonFromServer) => {
             AsyncStorage.setItem("datakey", JSON.stringify(responseJsonFromServer));
        })
      }

And in class B , you use the componentDidMount to retrieve the information from async-storage using the key declared for your data and save them in state as done below

this.state = {
        FirstName: "",
        OtherData: ""
    }
    componentDidMount(){
        AsyncStorage.getItem("datakey").then((data) =>{
          const val = JSON.parse(data);
          this.setState({
            FirstName: data.firstname,
            OtherData: data.otherdata,
          })
        })
      }

You may now display the data in your render function like this

View>
  <Text>{this.state.Firstname}</Text>
  <Text>{this.state.OtherData}</Text>
</View>

I hope this helps

Upvotes: 1

Asad
Asad

Reputation: 573

Use global variable like that

  import React, { Component } from "react";
    import FindUser from './FindUser';
    let findUser = new FindUser();

    class ShowProfile extends Component{
    construct(props) {
    super(props);
    global.Fusername=""; 
    global.Lusername=""; 
    }
    //...

    render() {
        return (
          <View style={style.container}>
            <KeyboardAwareScrollView>
              <View style={style.page}>
                <Text style={visualProfilo.text}>Name:</Text>
                <Text style={visualProfilo.text1}>{global.username}</Text>
                <Text style={visualProfilo.text}>Surname:</Text>
                <Text style={visualProfilo.text1}>{global.Lusername}</Text>
    //...
    }


    class FindUser extends Component {
        constructor(props){
            super(props);
            this.state = {
            }
        }

        findUser(cf) {
            let params = {};
            params = {
              "Person.FiscalCode": cf
            };
            //... query to DB
              .then(response => {
                let utente = response.docs[0];
                console.log("name: ", user.Person.FirstName)
    global.Fusername = user.Person.FirstName
global.Fusername = user.Person.LastName

The global scope in React Native is variable global. Such as global.foo = foo, then you can use global.foo anywhere.

A good practice to define global variable is to use a js file. For example global.js

global.foo = foo;
global.bar = bar;

Then, to make sure it is executed when project initialized. For example, import the file in index.js:

import './global.js'
// other code

Now, you can use the global variable anywhere, and don't need to import global.js in each file. Try not to modify them!

Upvotes: 0

Related Questions