FirebaseのFirestoreで データを登録する

FirebaseのFirestoreで データを登録する

Firebase 10.1.0

 

import { StatusBar } from 'expo-status-bar';
import { StyleSheet, Text, View, Button } from 'react-native';
import React from 'react';
import { TextInput } from 'react-native';
import {collection, addDoc,getFirestore } from 'firebase/firestore';

const firebaseConfig = {
  apiKey: "AIzaSuQ",
  authDomain: "samplom",
  projectId: "sampl0",
  storageBucket: "sampleom",
  messagingSenderId: "44230",
  appId: "1:4422a07"
};

if(getApps().length == 0){
  const app = initializeApp(firebaseConfig);
}

const db = getFirestore();


class Contents extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      theme:"",
      name:""
    }

    this.addItem = this.addItem.bind(this);
  }

  addItem(){
    const theme = this.state.theme;
    const name = this.state.name;
    const itemsCollection = collection(db, 'items');
    addDoc(itemsCollection,{theme, name});
  }

  render(){
    return(
      <View>
        <Text>タイトル</Text>
        <TextInput
            value={this.state.theme}
            onChangeText={text => this.setState({theme:text})}
            style={{borderWidth:1}}
        />
        <Text>名前</Text>
        <TextInput
            value={this.state.name}
            onChangeText={text => this.setState({name:text})}
            style={{borderWidth:1}}
        />
        <Button
            title="追加"
            onPress={this.addItem}
        />
      </View>
    )
  }
}

export default function App() {
  return (
    <View style={styles.container}>
      <Contents/>
      <StatusBar style="auto" />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

データの登録は、Firebaseのコンソールからも行える。

React環境でFirebase SDK v9のFirestoreでのCRUDの操作を学ぶ | アールエフェクト (reffect.co.jp)