0

enter image description hereI want to fetch data using this way:

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

const Home = () => {

  useEffect (async () =>{
    const response = await fetch('http://localhost:4000/user')
      const myJson = await response.json();
      console.log(JSON.stringify(myJson));
  })
 
  return(
    <div>
      <h1>Home Page</h1>
    </div>
  )
}

export default Home;

The result of localhost:4000 (generated with node js) is: { _id: 5da4a2066f90a24d4f82787a, name: 'Gregor', email: 'test@eee.com', age: 3, hasCar: false, favColors: [ 'green', 'red' ] }. The issue is that i can't fetch the data from this endpoint, but when i put a test API instead of my localhost, the code works. How to fetch data from that endpoint using my implementation? What is the probem of my code?

Here are my errors in console. enter image description here

enter image description here

  • `can't fetch the data from this endpoint`: Have any error or you can not fetch data inside useEffect ? What is display in console.log inside uesEffect ? – aldenn Oct 22 '19 at 18:03
  • Possible duplicate of [React Hook Warnings for async function in useEffect: useEffect function must return a cleanup function or nothing](https://stackoverflow.com/questions/53332321/react-hook-warnings-for-async-function-in-useeffect-useeffect-function-must-ret) – Joseph D. Oct 22 '19 at 18:06
  • What's the error you're getting? I would guess this is a CORS issue – Jake Luby Oct 22 '19 at 18:17
  • @jdn i posted 2 images with errors. –  Oct 22 '19 at 18:23
  • @Jake Luby, i posted 2 images with errors –  Oct 22 '19 at 18:23

1 Answers1

1

To get rid of that warning you need to extract the async piece to its own function. Something like:

useEffect (() => {

    const fetchData = async () => {
      const response = await fetch('http://localhost:4000/user')
      const myJson = response.json()
      console.log(JSON.stringify(myJson))
    }

    fetchData()
  }, [])

But that shouldn't be why you aren't able to get at the data. You need to be sure that the api at http://localhost:4000 has CORS enabled so react can communicate with it. If you don't have the ability to change that, then you'll need to set up a proxy: https://create-react-app.dev/docs/proxying-api-requests-in-development/

Jake Luby
  • 1,718
  • 5
  • 16