0

I fetch data and want to set state with newly received data. I have a special function for data fetching (loadData) and a component(App) where I have to setState. However, I can't pass there data from loadData. When I write const res = loadData(), I get Pending...

async function loadData() {
    let query = `someQuery`;

    let url = 'someUrl',
    options = {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        },
        body: JSON.stringify({
            query     
        })
    };

const response = await fetch(url, options);
const body = await response.json();
return body.data   // I have to set this data to state
}

const App = () => {
const [state, setState] = useState([])

useEffect(() => {
      loadData(); // here I would like to setState. How to pass in here data 
      received as a result 
          of loadData?
    }, [])
}
skyboyer
  • 22,209
  • 7
  • 57
  • 64
Loren
  • 49
  • 6
  • 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) – Emile Bergeron Jan 04 '21 at 20:12

2 Answers2

2

Of course you get Pending..., because it's a Promise.

What do you do with a Promise?
You can append .then(response => ...) to it in this case, because you can't await inside useEffect:

useEffect(() => {  
      loadData()  
          .then(response => setState(response.data.results));  
    }, [])  
Ergis
  • 1,105
  • 1
  • 7
  • 18
-1

loadData is an async function. That means, it returns Promise. In this case, you have to do await loadData() to access its result. Because function in useEffect can't be async, you have to wrap it in another function like this:

const App = () => {
    const [state, setState] = useState([])

    useEffect(() => {
        const wrappingFuncion = async () => {
            const res = await loadData();
            setState(res);
        }
        wrappingFunction();
    }, [])
}
Velrin Black
  • 412
  • 1
  • 4
  • 10