DEV Community

hirooka kazuya
hirooka kazuya

Posted on

dev diary 20251120

today i didn't sleep well, so my brain doesn't work. at least once a week there are such a days, stand with some music, soft drink, ect...

setting user name in app

on site display, there is the "hello ! ****" this user name is something kind of hash code because i don't set the username in this app. so i study how to set the username in this app,
in /amplify/data/resouce.ts

import { defineAuth, secret } from "@aws-amplify/backend";

export const auth = defineAuth({
  loginWith: {
    email: true,
  },
  userAttributes: {
    nickname: {
      required: true, 
      mutable: true, 
    },

    familyName: { 
      required: false, 
      mutable: true,
    },
    givenName: { 
      required: false, 
      mutable: true,
    },
  },
});
Enter fullscreen mode Exit fullscreen mode

and in app/setting/userProfileEditor.tsx

// app/setting/UserProfileEditor.tsx
'use client'
import React, { useState } from 'react';
import { updateUserAttributes } from 'aws-amplify/auth';

// 実際のAmplifyの型に合わせて詳細に定義しても良いですが、
// ここでは必要な構造だけを持つシンプルなインターフェースを定義します。
interface UserAttributes {
  nickname?: string;
  // 他に必要な属性(familyName, givenNameなど)があればここに追加
  [key: string]: any; // その他の属性を許容
}

interface UserProps {
  // Amplifyのユーザーオブジェクトはより複雑ですが、
  // attributesとusernameがあれば表示と更新には十分です。
  attributes?: UserAttributes;
  username?: string;
}

const UserProfileEditor = ({ user }: { user: UserProps }) => {
  // ユーザーの現在のニックネームを取得(未設定なら空文字)
  // 属性名はバックエンドの定義と同じ「nickname」を使用
  const initialNickname = user?.attributes?.nickname || '';
  const [nickname, setNickname] = useState(initialNickname);
  const [message, setMessage] = useState('');

// src/components/UserProfileEditor.tsx (handleUpdate 関数内)

const handleUpdate = async () => {
  setMessage('');
  try {
    // 戻り値のオブジェクト全体を受け取る
    const output = await updateUserAttributes({
      userAttributes: {
        nickname: nickname,
      },
    });

    // 💡 修正点 1: nextStep の有無と、その中のプロパティを確認する
    if (output.isUpdated) {
      // isUpdated プロパティが true の場合、更新が完了したことを示します
      setMessage('ニックネームが更新されました!');

    } else if (output.nextStep && output.nextStep.updateAttributeStep === 'CONFIRM_ATTRIBUTE_WITH_CODE') {
      // 💡 修正点 2: output.nextStep が存在し、
      // その中の updateAttributeStep プロパティを確認します

      // 確認コードが必要な場合の処理を記述
      setMessage('更新には確認コードの入力が必要です。'); 
      // 例: 確認コード入力フォームを表示する処理など

    } else {
       // その他の状態 (基本的に属性の更新では発生しにくい)
       setMessage('更新処理は完了しましたが、状態が確認できませんでした。');
    }

  } catch (error) {
    console.error('属性の更新に失敗しました:', error);
    // TypeScript環境下でエラーメッセージを使用する際、errorはunknown型になることがあるため、
    // 明示的にError型として扱うか、シンプルにメッセージを表示します。
    setMessage(`更新失敗: ${error instanceof Error ? error.message : '不明なエラー'}`);
  }
};

  return (
    <div>
      <h2>プロフィール編集</h2>
      <p>現在のニックネーム: {initialNickname || '未設定'}</p>
      <input
        type="text"
        value={nickname}
        onChange={(e) => setNickname(e.target.value)}
        placeholder="新しいニックネーム"
      />
      <button onClick={handleUpdate}>ニックネームを保存</button>
      {message && <p>{message}</p>}
    </div>
  );
};

export default UserProfileEditor;
Enter fullscreen mode Exit fullscreen mode

but now error occur at output.nextStep.updateAttributeStep

Top comments (0)