0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

React-NativeでContextにユーザオブジェクトを保持する

Last updated at Posted at 2021-11-23

記事の目的

  • ログイン中のユーザ情報をContext上に保持し再利用できるようにする
  • 必要な最小限の作業を5Stepで整理する

前提と課題

  • ReactNativeでContextを利用する
  • アプリはクラスでコンポーネント(画面)を作っている -> フックを直接呼べない
  • firebase周りはv9系で大きく書き方が異なるため、読替が必要

環境

  • Firebaseはv8系
  • Expo 4.13.0

手順

  • 手順の概要
  1. AuthProviderを作成
  2. AuthProviderを設置
  3. AuthContextを読み込み、useAuthContextフックを用意する
  4. フックから必要なstateを呼び出す。それをコンポーネントの引数に渡す
  5. propに渡されたuserを利用する
  • コード例
  • プロジェクトのトップ階層にAuthContextを設置 1/5
AuthContext.js
import React, { createContext, useState, useContext,useEffect } from 'react';
import * as firebase from 'firebase';
import 'firebase/firestore';
const AuthContext = createContext();

export function useAuthContext() {
  return useContext(AuthContext);
}

export function AuthProvider({ children }) {
  const [user, setUser] = useState('');

  const value = {
    user,
  };

  useEffect(() => {
    const unsubscribed = firebase.auth().onAuthStateChanged((user) => {
      setUser(user);
    });
    return () => {
      unsubscribed();
    };
  }, []);

  return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
}

  • Appでコンテクストを効かせる範囲のコンポーネントをAuthProviderに組み込む 2/5
App.js
import { AuthProvider } from './AuthContext'; // <-AuthProviderを読み込む

export default function App() {
  const Stack = createStackNavigator();

  return (
    <AuthProvider>  <- ここと
      <NavigationContainer>
        <Stack.Navigator>
            <Stack.Screen name="Hone" component={Home} />
                    その他任意のページ
        </Stack.Navigator>
      </NavigationContainer>
    </AuthProvider> <- ここでかこ  );
}

  • Contextの情報(保持しているuser)を使用する
home.js
// コンテキストからのユーザ取得 3/5
// AuthContextを読み込み、useAuthContextフックを用意する
import { useAuthContext } from '../AuthContext';
export default function(props) {
  // コンテキストからのユーザ取得 4/5
  // フックから必要なstateを呼び出す。それをコンポーネントの引数に渡す(user={user})
  const { user } = useAuthContext();
  return <Home {...props} navigation={navigation} user={user} />;
}

class Home extends React.Component {
componentDidMount (){
    // コンテキストからのユーザ取得 5/5
    // propに渡されたuserを利用する
    console.log(this.props.user)
  }
}

  • propにuserを移し替える作業は、クラスから直接フックを呼べないために行っっているクラスを利用していない場合は直接フックを利用すればいい

参考

コンテクスト REACT公式
https://ja.reactjs.org/docs/context.html

【完全版】ReactのFirebase Authentication(認証)を基礎からマスターする
https://reffect.co.jp/react/react-firebase-auth#Cotext

0
0
1

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?