-1

I am new to frontend development, had an issue which I can't seem to be able to fix. I have a Spring-boot application with React frontend. I am trying to fetch data from frontend in useEffect. I can see in the network tab in the browser that I am getting a response, but it sets the state to empty.

import { useEffect, useState } from "react";

export default function Home() {
  let [items, setItems] = useState("");
  let [nrOfClick, setNrOfClicks] = useState(0);

  useEffect(() => {
    const dataFetch = async () => {
      await fetch("http://localhost:8080/api/hellotxt", {
        method: "get",
        mode: "no-cors",
      })
        .then((data) => data.text())
        .then((data) => setItems(data));
    };

    dataFetch();
  }, []);

  return (
    <div className="App">
      <h1>This is the home page</h1>
      <p className="App-intro">
        To get started, edit <code>src/App.js</code> and save to reload.
      </p>
      <p className="App-intro">
        Fetch data from spring-boot server: <code>{items}</code>
      </p>
      <p>
        Number of clicks <code>{nrOfClick}</code>
      </p>
      <button onClick={() => setNrOfClicks(nrOfClick + 1)}>Click ME</button>
    </div>
  );
}

Tried writing useEffect multiple ways, but it did not work. Hoping the state updates with the response from the fetch

binga58
  • 153
  • 7
devios
  • 1

1 Answers1

0

When you use mode: "no-cors", you recieve an opaque response. So even though you do see at the network tab the response, there's not much you can use. If you change your code like so, you can actually see what you get back on the console:

const dataFetch = async () => {
  await fetch("http://localhost:8080/api/hellotxt", {
    method: "get",
    mode: "no-cors",
  })
    .then((data) => console.log(data)
    .then((data) => setItems(data));
};

There is good info that you can read at:

Trying to use fetch and pass in mode: no-cors

https://fetch.spec.whatwg.org/#concept-filtered-response-opaque

Panos
  • 89
  • 1
  • 4