0

I'm trying to get data out of an API with fetch, I can console.log the result in the fetch but out of the fetch I can't reach the data.

So I got this fetchData.js file with the function in it:

export const fetchData = (url) => {
    
    return fetch(url)
        .then(response => response.json())
        .then(result => console.log(result))
        .catch(error => console.log('error', error))
}

and then in the app.jsx file I call the function like this:

import { fetchData } from "./fetchData";

const URL = "https://pokeapi.co/api/v2/pokemon"

function App() {
  let data = fetchData(URL);
  console.log(data);

//return etc

But the console.log(data) keeps saying "undefined".

Can somebody please help me?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
bosman2
  • 39
  • 1
  • 2
  • 7
  • You're calling an async function and then not waiting for it to return before checking its value. – Daniel Beck Mar 04 '21 at 20:00
  • 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) – chazsolo Mar 04 '21 at 20:01
  • 1
    That's true, but he should have seen a `Promise` in the log. Try removing the second `then`, i.e. `.then(result => console.log(result))`. It's returning `undefined` – user2740650 Mar 04 '21 at 20:02

2 Answers2

1

You have to wait for the asynchronous action to complete before logging it.

let data = fetchData(URL).then(() => {console.log(data);});

(also either remove then(result => console.log(result)) or return result from it)

T J
  • 42,762
  • 13
  • 83
  • 138
  • this will give me an error "App.jsx:26 Uncaught TypeError: Cannot read property 'then' of undefined" – bosman2 Mar 04 '21 at 20:08
1

fetchData is an async function, that is why the console.log is executed before fetchData is resolved:

export const fetchData = async (url) => {  
    return fetch(url)
        .then(response => response.json())
        .then(result => (result)) //--> data
        .catch(error => console.log('error', error))
}

then in component, inside useEffect:

function App() {
  const [data, setData] = useState([]) //--> keep data in component state
  
  useEffect(()=> {
     fetchData(URL) //--> fetch data when component is mounted
      .then(response => setData(response))
  }, []);
  //...
}
lissettdm
  • 12,267
  • 1
  • 18
  • 39
  • aah yes this is working! only weird thing is when i put {data} in the return its gives an error but console.log(data) is working ? Uncaught Error: Objects are not valid as a React child (found: object with keys {devices}). If you meant to render a collection of children, use an array instead. – bosman2 Mar 04 '21 at 20:38
  • How are you render the content? check if data has the format that you are expecting – lissettdm Mar 04 '21 at 20:43