0

I want to fetch my local API. Please help. Here'a the code of my function:

    const [data, setData] = useState(null);

    async function fetchData() {
        const response = await fetch("https://localhost:44344/homeApi", {
            mode: "no-cors"
        });
        setData(await response.json());
    }

here's the error in Concole:

// pointing to this line => setData(await response.json());

    Uncaught (in promise) SyntaxError: Unexpected end of input
    at fetchData (DataComponent.js:11:1)
fetchData @ DataComponent.js:11
await in fetchData (async)
(anonymous) @ DataComponent.js:15
invokePassiveEffectCreate @ react-dom.development.js:23487
callCallback @ react-dom.development.js:3945
invokeGuardedCallbackDev @ react-dom.development.js:3994
invokeGuardedCallback @ react-dom.development.js:4056
flushPassiveEffectsImpl @ react-dom.development.js:23574
unstable_runWithPriority @ scheduler.development.js:468
runWithPriority$1 @ react-dom.development.js:11276
flushPassiveEffects @ react-dom.development.js:23447
(anonymous) @ react-dom.development.js:23324
workLoop @ scheduler.development.js:417
flushWork @ scheduler.development.js:390
performWorkUntilDeadline @ scheduler.development.js:157
TanyaNfyz
  • 21
  • 1

1 Answers1

0

You might want to use the useEffect hook of react.

 const [data, setData] = useState(null);


 useEffect(() => {
    async function fetchData() {
      let response = await fetch("https://localhost:44344/homeApi", {
        mode: "no-cors",
      });
      response = await response.json();
      setData(response);
    }

    fetchData();
  }, []);
Gray Singh
  • 320
  • 1
  • 11
  • 1
    careful, you shouldn't be using `async` within a `useEffect` hook the way you've shown above, see https://stackoverflow.com/questions/53332321/react-hook-warnings-for-async-function-in-useeffect-useeffect-function-must-ret – Sangeet Agarwal Jan 15 '22 at 14:52
  • a bit more on the subject of how to use `async` within a `useEffect` hook can be found at https://www.benmvp.com/blog/successfully-using-async-functions-useeffect-react/ – Sangeet Agarwal Jan 15 '22 at 15:36