useEffectの第二引数をうまく使うとよろしい
2023/4/2 8:37:00
うまくいったコード
const [post, set_post] = useState<Post | undefined>(undefined);
useEffect(() => {
if (post==undefined && post_id) {
(async () => {
const post_db = (await API.graphql({
query: getPost,
variables: { id: post_id },
authMode: "API_KEY",
authToken: awsExports.aws_appsync_apiKey
}) as GraphQLResult<GetPostQuery>).data?.getPost;
if (post_db) {
set_post(post_db)
}
console.log({ post_db });
})();
}
}, [post_id]);
うまくいかなかったコード(<Link>でDBが読み込まれなくなった・post==undefined
を外すと無限ループ)
const [post, set_post] = useState<Post | undefined>(undefined);
if (post==undefined && post_id) {
(async () => {
const post_db = (await API.graphql({
query: getPost,
variables: { id: post_id },
authMode: "API_KEY",
authToken: awsExports.aws_appsync_apiKey
}) as GraphQLResult<GetPostQuery>).data?.getPost;
if (post_db) {
set_post(post_db)
}
console.log({ post_db });
})();
}