1

I am trying to use Express (axios) to build a React app.

I was able to get an array of objects from MongoDB using get() method. Currently the list is printed out to the console. How can I assign it to a variable so that I could use that array for further actions?

useEffect(() => {
    const expensesListResp = async () => {
      await axios.get('http://localhost:4000/app/expenseslist')
      .then(
        response => console.log(response.data))
    }
    expensesListResp();
  }, []);

Many thanks!

rumon
  • 466
  • 2
  • 8
  • 21
  • Does this answer your question? [How do I save the axios response to variable, to be used outside axios?](https://stackoverflow.com/questions/56719812/how-do-i-save-the-axios-response-to-variable-to-be-used-outside-axios) – Subodh Ghulaxe Jun 14 '21 at 06:08

2 Answers2

3

You can assign it in the following way, let's say you have an array posts:

const [posts, setPosts] = useState([]);

useEffect(() => {
  axios.get('url')
  .then(res => setPosts(res.data))
  .catch(err => console.log(err));
}, [])

In your code, you can do it in this way:

const [resultArray, setResultArray] = useState([]);

useEffect(() => {
    const expensesListResp = async () => {
      await axios.get('http://localhost:4000/app/expenseslist')
      .then(
        response => setResultArray(response.data))
    }
    expensesListResp();
  }, []);
Suresh Mangs
  • 705
  • 8
  • 19
2

I am assuming that you have data printed on the console.log(response.data) and you want it to be assigned to a variable so that you can use it right?

if that's the case you are already using async function just name it with whatever variable name you want it to be before await.

for example:

const expensesListResp = async () => {
      const "your variable name" = await axios.get('http://localhost:4000/app/expenseslist')
    }

you can also save that variable in your state, if you want to use that variable data throughout your application.

Farrukh Ayaz
  • 310
  • 3
  • 15