Search code examples
javascriptreactjsecmascript-6axioses6-promise

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!


Solution

  • 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.