1

My http requests response returns an Object and I don't know how to assign it to a local variable and use it around between different files. How would i do that?

    axios.post(url + '/qget?sub=' + sub)
    .then(data => console.log(data))
    .catch(err => console.log(err)); 

I just want to take the response data and assign that to a variable I could export and use in my other files

noetix
  • 4,773
  • 3
  • 26
  • 47
Nen
  • 125
  • 1
  • 9
  • Possible duplicate of [How to return value from an asynchronous callback function?](https://stackoverflow.com/questions/6847697/how-to-return-value-from-an-asynchronous-callback-function) – Code-Apprentice Mar 10 '19 at 21:50
  • 1
    Check the above link for some tips. It also has a link to another related question. – Code-Apprentice Mar 10 '19 at 21:50
  • @Code-Apprentice those didn't help I even tried declaring the variable as global and it refused to read it in the then and just redeclared that there – Nen Mar 10 '19 at 22:06
  • Please [edit] your question to show what you have tried. – Code-Apprentice Mar 10 '19 at 22:10

2 Answers2

2

You could export a function which accepts data as a parameter from another module. Then you can call that exported function within the then callback so that the other module now has access to the http data.

some module:

export function doSomethingWithData(data) {
    // logic...
}

original file:

// ...

import { doSomethingWithData } from './someModule'

// ...

axios.post(url + '/qget?sub=' + sub)
.then(data => {
    console.log(data)
    doSomethingWithData(data)
})
.catch(err => console.log(err)); 

// ...
Talha
  • 807
  • 9
  • 13
1

Use localStorage that is part of Web Storage API:

axios.post(url + '/qget?sub=' + sub)
    .then(data => localStorage.setItem('storedData',data))
    .catch(err => console.log(err)); 

And then each time you retrieve it with localStorage.getItem:

let retrievedData = localStorage.getItem('storedData');

Note: never treat localStorage as secure, thus don't store any confidential data

About localStorage:

https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

Nikola Kirincic
  • 3,651
  • 1
  • 24
  • 28