next version: 13.3.1
The point is: using getServerSideProps
is working but using react useEffect
don't.
I plan to use useEffect
to fast update when I create a new post on strapi.
following the Page script:
import { useEffect, useState } from "react";
import { gql } from "@apollo/client";
import { ApolloClient, InMemoryCache } from "@apollo/client";
import { GetServerSideProps } from "next";
// Apollo Client Configuration
const client = new ApolloClient({
uri: process.env.API_URL,
cache: new InMemoryCache(),
});
// Define your GraphQL query
const GET_JOBS = gql(`
query Data {
jobs {
data {
attributes {
title
}
}
}
}`);
export default function Test({ jobs }: any) {
// const [data, setData] = useState(null)
console.log("SERVER_SIDE_PROPS >> ", jobs);
// output with data - working
useEffect(() => {
const fetchJobs = async () => {
try {
const { data } = await client.query({
query: GET_JOBS,
});
console.log("Jobs:", data.jobs.data);
// output - TypeError: Cannot destructure property 'data' of '(intermediate value)' as it is undefined.
//at fetchJobs (index.tsx:33:17)
} catch (error) {
console.error(error);
}
};
const fetchJobs2 = async () => {
try {
const response = await client.query({
query: GET_JOBS,
});
console.log("Complete response:", response);
// output - Complete response: undefined
} catch (error) {
console.error("Error from server:", error);
}
};
fetchJobs();
fetchJobs2();
}, []);
return (
<div>
<h1>Test</h1>
</div>
);
}
export const getServerSideProps: GetServerSideProps = async () => {
const { data } = await client.query({
query: GET_JOBS,
});
return {
props: {
jobs: data.jobs.data,
},
};
};