I'm trying to create a basic react app and having trouble formatting my fetch request for .JSON. The request should accept headers. Here's what I have for my component. I'm very new to this, so I'm assuming the issue is somewhat easy to fix, I'm just not seeing it.
import React, {useEffect} from 'react';
function Joke(){
function loadJoke (){
fetch("https://icanhazdadjoke.com/", {
headers: {
Accept: "application/json",
Accept: "text/plain",
},
})
.then((response ) => response.json())
.then ((data) => console.log(data))
}
useEffect(() => {loadJoke()})
return <h1>some funny joke goes here</h1>
}
export default Joke
The error I'm seeing says, "Uncaught (in promise) SyntaxError: Unexpected token ... is not valid JSON.
When I view my network in DevTools I see that I'm getting JSON data, so I'm not sure why it's throwing this error. Any ideas?
I've tried changing the syntax of my promises including messing around with the .then (response) method. No luck.
CodePudding user response:
I could't reproduce your error message exactly, but if you remove the second "Accept" it's working, as below. Keep the "application/json" since that's the content you're expecting.
I added the empty dependency array to useEffect
, so it only runs once.
Also, I added a state value to render it in the h1.
function Joke() {
const [joke, setJoke] = useState("");
useEffect(() => {
fetch("https://icanhazdadjoke.com/", {
headers: {
Accept: "application/json"
}
})
.then((response) => response.json())
.then((data) => setJoke(data.joke));
}, []);
return <h1>{joke}</h1>;
}
export default Joke;