'Next.js, Strapi - Fetch response is empty
I have nextjs frontend that fetch data from strapi backend. Problem is that data is empty even if i can see on strapi dev logs that request has been made.
This is next.js code
import { useRouter } from "next/router";
import React, { useEffect } from "react";
const Room = () => {
const router = useRouter();
let fetchData;
useEffect(() => {
if (router.asPath !== router.route) {
getDataNames();
}
}, [router]);
const getDataNames = () => {
try {
fetch("http://localhost:1337/rooms?_id=" + router.query.id)
.then((response) => response.json())
.then((data) => (fetchData = data));
console.log(fetchData);
} catch (e) {
console.error(e);
}
};
return (
<div>
<p>{router.query.id}</p>
<p>{fetchData}</p>
</div>
);
};
export default Room;
And here is the strapi log
[2021-02-23T14:06:20.845Z] debug GET /rooms?_id=6034aac1ba63472e9878ed25 (27 ms) 200
But I don't know why is data empty. Truth is that the response consist of base64 long text but I am not sure if that can cause the problem. Thanks in advance for any help.
Solution 1:[1]
const Room = () => {
const router = useRouter();
//let fetchData;
const [fetchData, setFetchData] = React.useState('');
useEffect(() => {
if (router.asPath !== router.route) {
getDataNames();
}
}, [router]);
const getDataNames = () => {
try {
fetch("http://localhost:1337/rooms?_id=" + router.query.id)
.then((response) => response.json())
.then((data) => { setFetchData(data); });
console.log(fetchData);
} catch (e) {
console.error(e);
}
};
return (
<div>
<p>{router.query.id}</p>
<p>{fetchData}</p>
</div>
);
};
You can use useState
hook for React state.
Solution 2:[2]
fetch
and set state are both asynchronous, so your code will get to console.log(fetchData);
while the fetch and the set state are both still being run.
If you add another useEffect for when fetchData
is changed you'll see the updated value.
useEffect(() => {
console.log(fetchData);
}, [fetchData]);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | kyun |
Solution 2 | martinedwards |