I am trying to access a query from my frontend react page. When I call the query this
import React from "react";
import { useQuery } from "@apollo/react-hooks";
import { getBookQuery } from "../queries/queries";
export const BookDetails = (props) => {
const { loading, error, data } = useQuery(getBookQuery, {
skip: !props.bookId,
variables: { id: props.bookId },
});
let content;
if (loading) content = <p>Loading Detail...</p>;
if (error) {
content = <p>Error...</p>;
}
if (!props.bookId) {
content = <p>No book selected yet</p>;
} else {
console.log(data.book);
const book = data;
}
return (
<div id="hook-details">
</div>
);
When I run this code I see the error TypeError: Cannot read property 'book' of undefined
To fix this error I changed the above code to use else if statements instead of just if statements, but I am failing to understand why this fixes the bug. Even when I throw log statements in each if block the same code seems to be called at the same time.
Working Code:
import React from "react";
import { useQuery } from "@apollo/react-hooks";
import { getBookQuery } from "../queries/queries";
export const BookDetails = (props) => {
const { loading, error, data } = useQuery(getBookQuery, {
skip: !props.bookId,
variables: { id: props.bookId },
});
let content;
if (loading) content = <p>Loading Detail...</p>;
else if (error) {
content = <p>Error...</p>;
}
else if (!props.bookId) {
content = <p>No book selected yet</p>;
} else {
console.log(data.book);
const book = data;
}
return (
<div id="hook-details">
</div>
);
};
Thank you.
Aucun commentaire:
Enregistrer un commentaire