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.
Advertisement
Answer
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.