简体   繁体   中英

How to export and Import user Id in React-Native

I need to get the user ID from API and then attach it on a variable maybe, so I can export it and then use it as value in other object. Can someone help me with example how can I do it? I'm stuck only on displaying it on the console.

Here is my code:

class LoginScreen extends Component {

  constructor(){
           super();
           this.state = {
            email: '',
            password: '',
            id: 0,
            result: false,
           }
       }

    _userLogin() {
      
         let email = this.state.email;
         let password = this.state.password;
         
         if (email && password) { 
           fetch("https://URL/api/login", {
             method: "POST",
             headers: {
               'Content-Type': 'application/json'
             },
             body: JSON.stringify({
               email: email,
               password: password,
             })
            })
           .then((response) => {
            if(response.status !== 200) {
              throw new Error('The given data was invalid.')
            }
            return response.json();
            })
           .then((responseData) => {
             this.renderResults(responseData)
             console.log(responseData)
             this.props.navigation.navigate('IntroScreen');
           })
           .catch((err) => console.log(err.message))
         }
       }

    componentDidMount () {
      fetch("https://URL/api/login", {
             method: "GET",
            })
          .then((response) => response.json())
          .then((responseJson) => {
             this.setState({getId: responseJson});
             console.log(responseJson.data.id);
             const id = responseJson.data.id;
          })
          .catch((error) => {
              console.error(error);
          });
    }

       renderResults = (responseData) => {
           if(responseData){
                this.setState({
                    result: true
                })
           }
       }

       handleEmail = (text) => {
             this.setState({ email: text })
       }


       handlePassword = (text) => {
             this.setState({ password: text })
       }

       errorMessage = () => {
         Alert.alert(
           'Error',
           'The given data was invalid.',
           [
            {
              text: "OK",
              style: "cancel"
            },
           ],
          { cancelable: false }
         )
       }

  render() {
    return (...)

After I attach it on variable I want to use it in other object like:

class HomeScreen extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
         currentDate: new Date(),
         markedDate: moment(new Date()).format("YYYY-MM-DD"),
         isLoading: true,
         id: 1, <------- HERE
         name: '',
         floor: 0
        };
    }

Here is a quick code snippet to fix your issue.

Create a singleton class, gloablParams.js like the following

class GlobalParams {
  constructor() {
    this.id = null;
  }
  userId = (id)=>{
    if(!id) return this.id;
    this.id = id;
  }
}
const instance = new GlobalParams()
export default  instance;

Now in LoginScreen , you can import it like this

import gp from './gloablParams'; 

Now call this function after login is successful, I think its componentDidMount or _userLogin and provide the id to save it.

componentDidMount() {
 fetch("https://URL/api/login", {
  method: "GET",
 })
  .then((response) => response.json())
  .then((responseJson) => {
   this.setState({ id: responseJson.data.id });
   gp.userId(responseJson.data.id); //save it here
   console.log(responseJson.data.id);
  })
  .then(gp.userId(id))
  .catch((error) => {
   console.error(error);
  });
}

Now you can import it, in the same way, like I wrote above, and access the userid from the same function but without arguments

gp.userId() //without any arguments

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM