I have a React project using Graphql and Mongo. When doing a query, I'm trying to log the returned data in the console through dot notation and it return "undefined".
I can't fathom Why??
My Component:
import { useQuery } from "@apollo/client";
import React, { useEffect } from "react";
import { GET_USER_SETTINGS } from "../graphql/getUserTimeSetting";
const UserAuthSettings = ({ isAuthenticated, toggle, user = { name: "" } }) => {
const { data, loading, error } = useQuery(GET_USER_SETTINGS, {
variables: { userName: user.name },
options: {
awaitRefetchQueries: true,
},
});
console.log(data.userTimeSetting);
if (loading) return <div>Submitting...</div>;
if (error) return <div>{error.message}</div>;
return null;
};
export default UserAuthSettings;
Ok I found the answer.
To use or "consume" the data with Apollo/client hooks, you need to do it once you make sure the data exist.
In other words, the code block
if (loading) return <div>Submitting...</div>;
if (error) return <div>{error.message}</div>;
must come before my console.log(data) - otherwise the query is still in flight and react could not verify the existence of the data. Hence the error.
Fantastic, moving one.