ログイン後にハートを押してからページをリロードしたり、他のページに移動して戻ると、押したはずのハートが再び白色(🤍)に見る。
分析の結果、ログイン後に「いいね」ボタンを押した時に状態は保存されているが、ページをリロードしたり他のページに行って戻ると、ハートの状態が初期化されてしまっていた。
これは、ページの読み込み時に「ユーザーがすでにいいねしたアイテムの状態」を確認していないことが原因だった。
解決:
/api/gacha/user-hearts エンドポイントを追加し、ログイン中のユーザーが「いいね」したガチャの一覧を返すようにした。
# --- /api/gacha/user-heartsエンドポイントを追加し、ログイン中のユーザーが「いいね」したガチャの一覧を返すエンドポイント ---
@app.get("/api/gacha/user-hearts")
def get_user_hearts(authorization: str = Header(None)):
"""ログイン中のユーザーがいいねしたガチャ一覧を返す"""
if not authorization or not authorization.startswith("Bearer "):
return JSONResponse(status_code=401, content={"error": "ログインが必要です。"})
try:
# JWTトークンからユーザーIDを取得
token = authorization.split(" ")[1]
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
user_id = payload.get("sub")
if not user_id:
raise JWTError("Invalid token")
cursor = connection.cursor(dictionary=True)
cursor.execute("SELECT gacha_id FROM gacha_heart_log WHERE id = %s", (user_id,))
results = cursor.fetchall()
cursor.close()
# いいねしたガチャIDだけ返す
liked_gacha_ids = [row['gacha_id'] for row in results]
return JSONResponse(content={"liked_gacha_ids": liked_gacha_ids})
except JWTError:
return JSONResponse(status_code=401, content={"error": "不正なトークンです。"})
except Exception as e:
return JSONResponse(status_code=500, content={"error": str(e)})
フロントエンドの修正