2

I am creating a react native app and I'm getting data from an API. I need to assign specific data into a global variable. That means my API return JSON data like {user_Id:"1' user_name:'abc' user_email:'abc@gmail.con'}. I need to assign user_Id into a global variable to access that in all of my screens.

This is what I tried;

componentDidMount() {
    const arrFinal = [];
    const {userDel} = this.state;
    fetch('my API url')
      .then(response => response.json())
      .then(responseJson => {
        // console.warn(responseJson);
        arrFinal.push(responseJson);
        arrFinal.map((item, index) => {
         global.UserID = item.user_Id
      })
      .catch(error => {
        console.error(error);
      });
   console.error(global.UserID)
  }

But here nothing will print on console. How can I fix this problem?

Sidath
  • 379
  • 1
  • 9
  • 25

1 Answers1

0

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise

componentDidMount() {
    const arrFinal = [];
    const {userDel} = this.state;
    fetch('my API url')
      .then(response => response.json())
      .then(responseJson => {
        // console.warn(responseJson);
        arrFinal.push(responseJson);
        arrFinal.map((item, index) => {
         global.UserID = item.user_Id
         console.error(global.UserID)
      })
      .catch(error => {
        console.error(error);
      });
   // console.error(global.UserID)
  }

or :

async componentDidMount() {
        const arrFinal = [];
    const { userDel } = this.state;
    const response = await fetch('my API url');
    const responseJson = await response.json();
    // console.warn(responseJson);
    arrFinal.push(responseJson);
    arrFinal.map((item, index) => {
      global.UserID = item.user_Id;
      console.error(global.UserID);
    });
    console.error(global.UserID);

  }

ebyte
  • 1,469
  • 2
  • 17
  • 32