-2

I have a React app in in which I have to make calls to an API. I created a dataService.js where I will create all the functions with the calls to my API.

In the component in which I need to retrieve the data, I simply try to console.log the data but I have a Promise {<pending>} instead of the result I need... What can I do to retrieve the data ?

My initial idea is to retrieve all the data I need using this dataService.js and setting the state of the component with the data. I guess it is possible but how ?

dataService.js:

export const dataService = {dataValue};

function dataValue() {
    return axios.get('url/to/api')
        .then(response => {
            console.log(response.data.soc) //this works well !
            let soc = response.data.soc
            return soc;
        });
}

myComponent.js:

class myComponent extends Component {
    render() {
        let test = dataService/dataValue(); // I imported the dataService !
        console.log(test);
        return (<div></div>);
    }
}
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Thbwun
  • 323
  • 1
  • 3
  • 14
  • 4
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – takendarkk Jul 15 '20 at 14:41
  • have you searched for existing questions/answers? this is not a unique question – Peter Jul 15 '20 at 14:49

2 Answers2

0

First of all, I recommend using React Hooks, combined w/ Function Components to retrieve data. Something like this:

MyComponent.js

import React, {useEffect, useState} from 'react';
import axios from 'axios';

const MyComponent = () => {
  const [data, setData] = useState([]);

  useEffect(() => {
    axios.get('url/to/api')
        .then(response => {
            setData(response);
        });
  }, []);

return (<div>{data.map(d => <<DO WHATEVER YOU WANT W/ DATA HERE>>)}</div>);
}
StefanN
  • 871
  • 6
  • 19
-1

Making an API request is asynchronous. So u need an async function here

const dataValue = async () => {
    const response = await axios.get('url/to/api');
    return response.data.soc;
}
Praveen Dass
  • 586
  • 1
  • 3
  • 13