react-hooksclient-serverfetch-apipreact

Why does res.text() not work inside useEffect()?


On islands/test.tsx I have:

import { useEffect } from "preact/hooks";
export default function Test(){ 
    fetch('https://example.com')
    .then(res => res.text())
    .then(d => console.log(d))
    
    useEffect(() => {        
        fetch('https://example.com')
        .then(res => res.text())
        .then(d => console.log(d))     
    })
    return 'hi'
}

The data returns fine in the server's console (the part outside the useEffect() hook), but it doesn't show up in the client's console. However if I change the fetch function to:

fetch("https://jsonplaceholder.typicode.com/todos/1")
.then(res => res.json())
.then(d => console.log(d))

then it shows on both sides. Why is that the case?


Solution

  • Not related to useEffect here. It works for both cases. Why do you not see the message in the client? Because of CORS https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

    The second API (https://jsonplaceholder.typicode.com/todos/1) works because it public API that allows * already.