LoginSignup
0
0

More than 1 year has passed since last update.

React( ReduxToolkit + TypeScript)の構成でアプリを作成をしました【Blog App】

Last updated at Posted at 2022-07-18

環境の準備

①ターミナルでreactアプリケーションを作成する。

npx create-react-app <プロジェクト名> --template redux-typescript
cd <プロジェクト名>
yarn start

② 必要なパッケージをインストールする。

ESLintとPrettierとを基本からまとめてみた【React+TypeScriptのアプリにESLintとPrettierを導入】

yarn add react-router-dom
npm install @reduxjs/toolkit react-redux
npm i --save-dev @types/uuid
yarn add moment
yarn add react-markdown

公式サイト: Tailwind CSS

npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p

コンポーネント・ファイル構成

  src
   ├─ components
        ├── Button.tsx
        ├── Header.tsx
        ├── TextField.tsx
        └── TextTitle.tsx
   ├─ features
        ├── AddUser.tsx
        ├── EditUser.tsx
        ├── UserList.tsx
        └── userSlice.ts
   ├── App.tsx
   ├── index.css
   ├── index.tsx
   └── store.ts
├── tailwind.config.ts

ログインしている時としていない時で表示を変える

理由 : 投稿者(ログイン者)が投稿した内容を一般ユーザー(ログイン者でない)が編集や削除できないようにしたいから。

① ログインしていない時は『LogIn』のボタンのみでログインしている時は、『Admin page』と『Log Out』が表示されるようにしたい。
② ログインしていない時は投稿内の『編集』『削除』のボタンが非表示で、ログインしている時は、投稿内の『編集』『削除』のボタンが表示されるようにしたい。

1.ライブラリの aws-amplify にある Auth クラスで現在のユーザを取得できるメソッド 『currentUserInfo()』 を利用する。
2.ログイン有無の情報をコンテキストか何かに保存して他のコンポーネントで流用する。

sample.js
const [isLogin, setIsLogin] =  useState(false) 
  Auth.currentUserInfo().then((user) => {
      if ( user == null) setIsLogin(true)
      else if ( user != null ) setIsLogin(false)
    }).catch((e) => {
      console.log(e);
    });

3.Header.tsx 以外にも変えたい箇所があるので、App.tsx で currentUserInfo() の処理を書いて、変えたい箇所があるコンポネートにログイン状態の有無を『props』で渡す。
4.下記のように Header.tsx に『props』として受け取ることで App.tsx の isLogin が使用できる。

src/App.tsx
const [isLogin, setIsLogin] = useState(false);
  Auth.currentUserInfo()
    .then((user: any) => {
      if (user == null) setIsLogin(true);
      else if (user != null) setIsLogin(false);
    })
    .catch((e: any) => {
      console.log(e);
    });

 省略
return (
    <>
      <div className='flex flex-col h-full bg-white shadow-lg max-h-16'>
        <Header isLogin={isLogin} />
      </div>
      省略
    </>
  );
src/components/Header.tsx
type Props = { isLogin: boolean };
const Header: React.FC<Props> = (props) => {
  const { isLogin } = props;
 省略
};

Amplify

1. Amplifyの組み込み
//Amplify CLIをグローバルインストール
npm i @aws-amplify/cli@8.4.0
or
yarn global add @aws-amplify/cli@8.4.0

//インストールが出来ているか確認
yarn global list

//Amplify CLI を使用するための初期設定を開始する
amplify configure

//Specify the AWS Region
? region:
> ap-northeast-1   を選択する

? user name: <プロジェクト名>

AWS画面

✅ アクセスキー - プログラムによるアクセル  を選択する

✅ AdministratorAccess-Amplify  を選択する

※ タグの追加(オプション)は、特に追加しなくても良い

入力に問題なければ、『ユーザーの作成』をする

『アクセスキーID』と『シークレットアクセスキー』は念の為
『.CSVのダウンロード』を行う

Press Enter to continue 
『Enter』を押す

? accessKeyId: 『アクセスキーID』
? secretAccessKey:『シークレットアクセスキー』
? Profile Name: <プロジェクト名>
amplify init

? Enter a name for the project  //Defaultでよければ Enter
? Initialize the project with the above configuration? No
? Enter a name for the environment:  main
? Choose your default editor: Visual Studio Code
? Choose the type of app that you're building: Javascript 
? What javascript framework are you using: react
? Source Directory Path: src
? Distribution Directory Path: build
? Build Command: npm run-script build
? Start Command: npm run-script start
? Select the authentication method you want to use: AWS profile
? Please choose the profile you want to use: <プロジェクト名>
? Help improve ify CAmplI by sharing non sensitive configuration on
failures : yes
2. AmplifyAuthを用いたユーザ認証機能の実装する

① AWSマネジメントコンソールの画面で、『AWS Amplify』を検索して、
『AWS Amplify』を選択する。

② 『新しいアプリケーション』をクリックし、『ウェブアプリケーションをホスト』
を選択する。

③ Amplify Hostingの開始で、『Github』を選択する。

④ リポジトリブランチの追加で『🔁』を押して、最近追加されたリポジトリを選択し、
『main』ブランチを選択し、『次へ』を押す。

⑤構築設定の構成は、何もせず『次へ』を押し、確認画面で『保存してデプロイ』を押す。

⑥Yor app successfullyが出ていたら成功。下のhttps//をクリックする。

⑦ 『Backend environments』をクリックして初期化する。

npm i aws-amplify @aws-amplify/ui-react 

amplify add auth

Do you want to use the default authentication and security 
configuration? : Default configuration

How do you want users to be able to sign in? :e-mail
Do you want to configure advanced settings?: No, I am done.

amplify state
amplify push --y
App.js
import { Amplify } from "aws-amplify";
import { withAuthenticator } from "@aws-amplify/ui-react";
import '@aws-amplify/ui-react/styles.css';
import awsExports from "./aws-exports";
Amplify.configure(awsExports);

3. Amplify DataStoreでCRUD機能を実装する
① aws-amplifyライブラリの追加
yarn add aws-amplify@4.3.24
index.js
import {Amplify} from "aws-amplify"
import awsExports from "./aws-exports"
Amplify.configure(awsExports)
② AmplifyCLIを用いたAPIの追加
amplify add api

? Select from one of the below mentioned services: GraphQL
? Here is the GraphQL API that we will create. Select a setting to 
edit or continue     Name:<プロジェクト名>
? Provide API name: <プロジェクト名>
? Here is the GraphQL API that we will create.
Select a setting edit or continue: 
Authorizationodes:API key(default, expiration time: 7 days from now)
? Choose the default authorization type for the API: API key
? Enter a description for the API key: <プロジェクト名>Gql AuthKey
? After how many days from now the API key should expire: 365
? Here is the GraphQL API that we will create. Select a setting to
edit or continue: Disabled
? Enable conflict detection? Yes
? Select the default resolution strategy: Auto Merge
? Here is the GraphQL API that we will create. Select a setting to
edit or continue: Continue
? Choose a schema template:
Sigle object with fields(e.g., "Todo" with ID, name, description)
? Do you want to edit the schema now:yes
③ スキーマの定義
//例 作成するアプリにより仕様を変更すること !

type User @model {
 title: String! 
 content: String !
 }
amplify push
? Are you sure you want to continue:   yes
? Do you want to generate code for your newly created GraphQL API:
yes 
? Choose the code generation language target : typescript
? Enter the file name pattern of graphql queries, mutations and 
subscriptions: Enterを押す
? Do you want to generata/update all possible GraphQL operations -
queries, mutations and subscriptions: Yes
? Enter maximum statement depth [increase from default if your schema is dedply nested] :2
? Enter the file name for the generated code: 
src/API.ts   //初期値のままでOK

// 成功し完了したら
GraphQL endpoint:
GraphQL API KEY:
4. 各種CRUD機能を実装する
①Create機能の実装

参考サイト

React Crud App with Redux Toolkit | React Redux Projects
【AWS入門】AWSを使ってReactアプリをデプロイしてみよう ~AWS Amplifyを使用~
AWSAmplifyを使用してReact認証フローを作成する
React( ReduxToolkit + Tailwindcss )の構成でアプリを作成をしました【CRUD Application 】
【AWS Amplify入門】第4回:Amplifyの組み込み
【AWS Amplify入門】第5-1回:DataStoreを用いたCRUD機能の実装~前編~
Amplify UIを使ってReactアプリにAmazon Cognitoの認証フォームを実装する
AWS Amplifyの公式チュートリアルでToDoリストアプリ(React)をデプロイしてみた
How to Build a Full Stack App with AWS Amplify and React

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0