0

this is my first time to develop a react application.

I will be using the get response of axios to populate a table. The outside var is declared and used outside the scope of the axios, and when I update that var inside the scope of axios, it does not update the var data outside, as per checking in debug.

Is there a way to use the get response of axios outside/ in global scope?

Thank you very much for your help.

//rows is declared outside the scope
let rows = [];

  axios
    .get(`url here`)
    .then(res => {
      for (let i = 0; i < res.data.length; i++) {
        //rows.push not reflecting on the react application (inside scope of res)
        rows.push(res.data[i]);
      }
    });

  //rows.push reflecting on the react application (outside scope of res)
  rows.push({
    test: 5.7
  });
Dan
  • 559
  • 4
  • 9
  • 23

1 Answers1

0

Use async functions

If you want code to run in an async way you need to use the async keyword and use await to wait for promises to be resolved.

Example

async function getData() {
  const rows = [];
  const res = await axios.get('url here');
  for (let i = 0; i < res.data.length; i++) {
    rows.push(res.data[i]);
  }
  rows.push({
    test: 5.7,
  });
}

Explanation

In your code the line with let rows = []; runs and then axios.get(... starts. then since the code is waiting for a promise it continues with rows.push({test: 5.7}); until the data is returned in the then

In my example each line runs when the previous is finished because we wait for data to return from the promise. It becomes easier to read. But be aware that the function getData now returns a promise. So anywhere that invokes the function getData will also have to await its response.

In React

If you're retrieving data in react there are some things you should know. If the first is, if the data is needed on load then put the request into the componentDidMount lifecycle method.

you will have to make it async though.

Example

async componentDidMount() {
  const data = await getData();
  this.setState({data});
}

This will cause an additional render when the component loads. There some more info about this here.

Alternatively you may want to get data with a state management library like Redux. In Redux you can use actions to get your data so that this process is removed from individual components and more easily shared between them via the library react-redux and the connect decorator.

Community
  • 1
  • 1
Joe Lloyd
  • 19,471
  • 7
  • 53
  • 81