I have an API endpoint located on my localhost:8000/
port; this endpoint simply returns the following object {"message": "hello"}
.
I would like to grab this object using my React JS script. My script is added below.
import React, {useEffect, useState} from "react";
const App = () => {
const [message, setMessage] = useState("");
const getHomePageData = async () => {
const requestOptions = {
method: "GET",
headers: {
"Content-Type": "application/json",
},
};
const response = await fetch("/", requestOptions)
if (!response.ok) {
console.log("Error in fetching the data!");
} else {
console.log("Data fetched correctly!");
}
return await response.json();
};
const data = getHomePageData();
console.log(data);
return(
<center><h1>Hello, world!</h1></center>
);
}
export default App;
Fetching the data seems to be working, because I'm getting the following log inside the console: Data fetched correctly!
thus I think everything is working alright with my backend. However on the next line I get the following error message: Unhandled Promise Rejection: SyntaxError: The string did not match the expected pattern.
How can I fix my code to be able to get the .json()
data?
CodePudding user response:
Try using useEffect
:
import React, {useEffect, useState} from "react";
const App = () => {
const [message, setMessage] = useState("");
useEffect(() => {
const getHomePageData = async () => {
try {
const requestOptions = {
method: "GET",
headers: {
"Content-Type": "application/json",
}
};
const response = await fetch("/", requestOptions)
const data = await response.json();
setMessage(data.message);
} catch (error) {
console.log(error);
}
};
getHomePageData();
}, []);
return(
<center><h1>Hello, world!</h1></center>
);
}
export default App;
CodePudding user response:
Majed's answer is probably the right way to wait for a promise in a react component without library.
However, if you are not too afraid to use library, tools like react-use-promise or react-query might help you to write more readable code.
const App = () => {
const [message, error, state] = usePromise(async () => {
const query = await fetch("/", {
method: "GET",
headers: {
"Content-Type": "application/json",
},
})
return await query.json();
},
[] // here the dependencies you use in your promise
);
return(
<center><h1>Hello, world!</h1></center>
);
}