I’m doing SSR with apollo and nextjs. So I’m calling a SSR function when loading my page using a apolloClient.query() function, passing the data as props to the component in the page.
I have a useEffect hook which runs after I add a new post to the database (dgraph), via useMutation, and inside that hook I rerun the same apolloClient.query() to get the newest data and re-render it. However, for some reason, when I call the query the second time, it always shows old data not the new data with new post. I thought it was a caching issue, but even when I pass "fetchPolicy: “network-only” " per their docs, it still doesn’t seem to return the new data. I know the database is being updated b/c after I refresh the page, I see the new data. I’ve been stuck for a while, any help would be most appreciated!
Here’s relevant code:
component.js
export default function Questions({ questionsInit, client }) {
const [questions, setQuestions] = useState({ ...questionsInit, status: "init"});
const [questionsChanged, setQuestionsChanged] = useState(true);
const [serverError, setServerError] = useState(null);
const [showAdd, setShowAdd] = useState(false);
useEffect(() => {
async function getQuestions() {
//this is the initial render, do not fetch code since it
//is already set from the server side
if (questionsChanged !== null) {
try {
const { data } = await client.query({query: GET_QUESTIONS_QUERY});
setQuestions({ ...data, status: 'success'});
} catch (err) {
setServerError({ message: err.message});
console.log(err.message);
}
}
}
getQuestions();
}, [questionsChanged]);
return (
<>
//component where questionsChanged is passed
</>
)
}
and my page/index.js where I’m initially calling the data via SSR:
export default function HomePage(props) {
return (
<>
<Questions{...props} />
</>
);
}
export async function getServerSideProps(context) {
const apolloClient = initializeApollo();
const { origin } = getAbsoluteUrl(context.req);
const questions = await apolloClient.query({query: GET_QUESTIONS_QUERY});
const users = await apolloClient.query({query: GET_USERS_QUERY});
// Here we are doing a query for the profile data.
// that we will pass in the messageInit props
return { props: { questionsInit: questions.data, userInit: users.data, origin } };
}