I using Apollo to fetch data from GraphQL. When I trying to log data from useQuery
I'm getting two logs first in undefined and second is log with gql data.
When I'm trying to get data from for example data.flats.title
react I have information that is undefined so it's info from first console.log()
. How I can get data and show it?
Console Screen:
import React from "react";
import { gql, useQuery } from "@apollo/client";
const myQuery = gql`
query {
flats {
Title
}
}
`;
const Test = () => {
const { data } = useQuery(myQuery);
console.log(data);
return <h2>GQL TEST</h2>;
};
export default Test;
It seems like you need a simple null
or undefined
check to represent your data properly. You can either use Ternary operator or &&
check.
Based on that you can do in your component with &&
as the following:
const Test = () => {
const { data } = useQuery(myQuery)
return <>
<h2>GQL TEST</h2>
{data && data.flats && <span>data.flats.title</span>}
</>
}
Or with Ternary operator:
const Test = () => {
const { data } = useQuery(myQuery)
return <>
<h2>GQL TEST</h2>
{data && data.flats ? <span>data.flats.title</span> : null}
</>
}
Just from the naming of data.flats
I can assume it can be an array where you need to use similarly as I suggested above just with .map()
as:
{data && data.flats && data.flats.map(e => <span>e.title</span>)}