SkyeBoniwell
SkyeBoniwell

Reputation: 7092

Convert an Axios promise to a regular JSON array

I'm trying to return data from a function, but it's giving me issues.

I need this function to return JSON, but it's returning a promise.

Here is the function:

import axios from 'axios';

const fetchData = async () => {
  const result = await axios(
    'https://localhost:44376/api/parts',
  );
  return JSON.stringify(result, null, 2);
};

export default fetchData;

It's throwing this error when I try to use the returned data:

Uncaught TypeError: data.map is not a function

When I write out to the console, here is what I see:

data from machineParts API call:

Promise {<pending>}
 [[PromiseStatus]]: "resolved"
    [[PromiseValue]]: {"data": [ { "id": 5, "title": "Steel Rods", "partId": 39482  etc...

But here is what I need it to return:

data from machineParts API call: (7) [ {...}, {...}, {...}, {...}, {...}, {...}, {...}]

0:
   id: 5
   title: "Steel Rods"
   partId: 39482

1:
   id: 23
   title: "Honed Cylinder head"
   partId: 23412      

etc...

Is there anyway to convert a promise to a JSON array?

Thanks!

Upvotes: 2

Views: 10959

Answers (3)

Chris Brenberg
Chris Brenberg

Reputation: 142

async and await are just a different syntax for handling promises, the 'await' more or less works the same as chaining a .then on the call to axios. Something like this should work in the module:

const fetchData = async () => {
  const response = await axios.get('https://localhost:44376/api/parts');
  return response.data;
};

Because fetchData() is an async function, it will return a Promise, so the calling code will either have to await the result or use .then syntax to access the resulting data.

Upvotes: 3

awran5
awran5

Reputation: 4536

You just want to call .then() after you calling fetchData function:

// fetchData.js
import axios from "axios";

const fetchData = async () => {
  const result = await axios(
    'https://localhost:44376/api/parts',
  );
  // return the result
  return result;
};

export default fetchData;

Now import it inside your component like so:

// App.js 
import fetchData from './fetchData' // fetchData path

const App = () => {
  const [data, setData] = React.useState([])

  React.useEffect(() => {

   fetchData().then(res => {
     setData(res.data)
   })
  },[])

  return (
    <div>
      <pre>
        <code> {JSON.stringify(data, null, 2)} </code>
      </pre>
    </div>
  )
}

export default App

See sandbox example.

Upvotes: 7

sdotson
sdotson

Reputation: 820

The answer is in the console you shared, the line starting with data from machineParts API call:. The array is nested under a data prop.

You're also JSON.stringifying the result, which would make it a string and no longer a string or object. That is why you are seeing the data.map is not a function error, because string doesn't have a prototype method named map.

To fix, change return JSON.stringify(result, null, 2); to return result.data;.

Upvotes: 1

Related Questions