Реагировать на родную экспозицию Firebase Firestore читать один предмет - PullRequest
0 голосов
/ 29 апреля 2020

Я хочу, чтобы результат ввода текста сохранял один элемент и удерживал его на экране редактирования профиля. Получение и хранение информации из Firebase Firestore. Я следовал учебному пособию о том, как загрузить информацию, но он загружается в массив, я хотел бы отдельных значений. Буду признателен за любую помощь, поскольку я все еще учусь.

My firebase. js

import * as firebase from "firebase";

// Optionally import the services that you want to use
//import "firebase/auth";
//import "firebase/database";
import "firebase/firestore";
import { findBreakingChanges } from "graphql";
//import "firebase/functions";
//import "firebase/storage";

// Initialize Firebase
const firebaseConfig = {
  apiKey: "",
  authDomain: "",
  databaseURL: "",
  projectId: "",
  storageBucket: "",
  messagingSenderId: "",
  appId: "1:",
  measurementId: "G",
};

firebase.initializeApp(firebaseConfig);

export function addItem(item, addComplete) {
  firebase
    .firestore()
    .collection("Users")
    .doc("userTest")
    .set({
      name: item.name,
      // age: item.name,
      createdAt: firebase.firestore.FieldValue.serverTimestamp(),
    })
    .then((snapshot) => snapshot.get())
    .then((itemData) => addComplete(itemData.data()))
    .catch((error) => console.log(error));
}

export async function getItems(itemsRetreived) {
  var itemList = [];

  var snapshot = await firebase
    .firestore()
    .collection("Users")
    .orderBy("createdAt")
    .get();

  snapshot.forEach((doc) => {
    itemList.push(doc.data());
  });

  console.log(itemList);
  itemsRetreived(itemList);
}

export default firebase;

Экран моего профиля. Я хотел бы, чтобы значение было добавлено в качестве переменной или ссылки в

    import React from "react";
import {
  StatusBar,
  Dimensions,
  ScrollView,
  Platform,
  View,
  StyleSheet,
  TextInput,
  Button,
  FlatList,
} from "react-native";
import styled from "styled-components";
import { Ionicons } from "@expo/vector-icons";
import { connect } from "react-redux";
import { AsyncStorage } from "react-native";
import AvatarProfile from "../components/AvatarProfile";
import { ProgressChart } from "react-native-chart-kit";
import { DataTable } from "react-native-paper";
import { TouchableOpacity } from "react-native-gesture-handler";
import { addItem, getItems } from "../components/Firebase";
import { ListItem, Divider } from "react-native-elements";

let screenWidth = Dimensions.get("window").width;
const screenHeight = Dimensions.get("window").height;
StatusBar.setHidden(true);

function mapStateToProps(state) {
  return { action: state.action, name: state.name };
}

class ProfileScreen extends React.Component {
  static navigationOptions = {
    title: "Profile",
    headerShown: false,
  };

  state = {
    itemList: [],
    currentItem: null,
  };

  onItemAdded = (item) => {
    this.setState((prevState) => ({
      itemList: [...prevState.itemList, item],
    }));
    console.log("Item Added");
    console.log(item);
  };

  onItemsReceived = (itemList) => {
    console.log(itemList);
    console.log("Items Received");
    this.setState((prevState) => ({
      itemList: (prevState.itemList = itemList),
    }));
  };

  componentDidMount() {
    getItems(this.onItemsReceived);
  }


  render() {
    const { navigate } = this.props.navigation;
    const data = this.state.itemList;
    return (
      <RootView>
        <Container>
          <ScrollView>
            <Header>
              <Background source={require("../assets/background-grass.jpg")} />
              <Name>{this.props.name}</Name>
            </Header>
            <AvatarView>
              <AvatarProfile />
            </AvatarView>
            <ScrollView
              style={{
                flexDirection: "row",
                padding: 20,
                paddingLeft: 12,
                paddingTop: 30,
                marginTop: 40,
              }}
              horizontal={true}
              showsHorizontalScrollIndicator={false}
            >
              {/* {evals.map((evalinfo, index) => ( */}
              {/* key={index} text={evalinfo.text}  */}
              <ItemContainer>
                <TouchableOpacity onPress={() => navigate("Eval1")}>
                  <Item>
                    <Text>Eval 1</Text>
                  </Item>
                </TouchableOpacity>

                <Item>
                  <Text>Eval 2</Text>
                </Item>
                <Item>
                  <Text>Eval 3</Text>
                </Item>
                <Item>
                  <Text>Eval 4</Text>
                </Item>
                <Item>
                  <Text>Eval 5</Text>
                </Item>
                <Item>
                  <Text>Eval 6</Text>
                </Item>
              </ItemContainer>
            </ScrollView>
            <Subtitle>{"User Info".toUpperCase()}</Subtitle>
            <View>
              <TextInput
                style={styles.input}
                placeholder="Add Item"
                value={this.state.currentItem}
                onChangeText={(text) =>
                  this.setState((prevState) => ({
                    currentItem: (prevState.currentItem = text),
                  }))
                }
              />
              <Button
                title="Submit"
                style={StyleSheet.button}
                onPress={() =>
                  addItem(
                    {
                      name: this.state.currentItem,
                    },
                    this.onItemAdded
                  )
                }
              />
            </View>
            <FlatList
              data={this.state.itemList}
              ItemSeparatorComponent={() => (
                <Divider style={{ backgroundColor: "black" }} />
              )}
              keyExtractor={(item, index) => index.toString()}
              renderItem={({ item }) => {
                console.log(item);
                return <ListItem title={item.name} onPress={() => {}} />;
              }}
            />

            <UserContainer>
              <DataTable>
                <DataTable.Header>
                  <DataTable.Title numeric>Age</DataTable.Title>
                  <DataTable.Title numeric>Height</DataTable.Title>
                  <DataTable.Title numeric>Weight</DataTable.Title>
                </DataTable.Header>
                <DataTable.Row>
                  <DataTable.Cell numeric>{}</DataTable.Cell>
                  <DataTable.Cell numeric>192</DataTable.Cell>
                  <DataTable.Cell numeric>89</DataTable.Cell>
                </DataTable.Row>
              </DataTable>
            </UserContainer>

            <Subtitle>{"Base Results".toUpperCase()}</Subtitle>
            <Content>
              <DataContainer>
                <DataTable>
                  <DataTable.Header>
                    <DataTable.Title>Composition</DataTable.Title>
                    <DataTable.Title numeric>Current</DataTable.Title>
                    <DataTable.Title numeric>Goal</DataTable.Title>
                  </DataTable.Header>
                  <DataTable.Row>
                    <DataTable.Cell>BMI</DataTable.Cell>
                    <DataTable.Cell numeric>7.8</DataTable.Cell>
                    <DataTable.Cell numeric>6.0</DataTable.Cell>
                  </DataTable.Row>

                  <DataTable.Row>
                    <DataTable.Cell>Fat</DataTable.Cell>
                    <DataTable.Cell numeric>25</DataTable.Cell>
                    <DataTable.Cell numeric>32</DataTable.Cell>
                  </DataTable.Row>
                  <DataTable.Row>
                    <DataTable.Cell>Muscle</DataTable.Cell>
                    <DataTable.Cell numeric>7.8</DataTable.Cell>
                    <DataTable.Cell numeric>6.0</DataTable.Cell>
                  </DataTable.Row>

                  <DataTable.Row>
                    <DataTable.Cell>KCAL</DataTable.Cell>
                    <DataTable.Cell numeric>25</DataTable.Cell>
                    <DataTable.Cell numeric>32</DataTable.Cell>
                  </DataTable.Row>
                  <DataTable.Row>
                    <DataTable.Cell>Metabolical Age</DataTable.Cell>
                    <DataTable.Cell numeric>7.8</DataTable.Cell>
                    <DataTable.Cell numeric>6.0</DataTable.Cell>
                  </DataTable.Row>

                  <DataTable.Row>
                    <DataTable.Cell>Viceral Fat</DataTable.Cell>
                    <DataTable.Cell numeric>25</DataTable.Cell>
                    <DataTable.Cell numeric>32</DataTable.Cell>
                  </DataTable.Row>
                </DataTable>
              </DataContainer>

              <Subtitle>Progress Chart</Subtitle>

              <ProgressChart
                data={{
                  data: [0.9, 0.6, 0.8, 0.6, 0.6, 0.8],
                }}
                width={screenWidth}
                height={285}
                chartConfig={{
                  backgroundColor: "#e26a00",
                  backgroundGradientFrom: "#fb8c00",
                  backgroundGradientTo: "#ffc733",
                  decimalPlaces: 2, // optional, defaults to 2dp
                  color: (opacity = 1) => `rgba(255, 255, 255, ${opacity})`,
                  style: {
                    borderRadius: 16,
                  },
                }}
                style={{
                  alignSelf: "center",
                  borderRadius: 26,
                  marginLeft: 20,
                  marginRight: 10,
                }}
              />
            </Content>
          </ScrollView>
        </Container>
      </RootView>
    );
  }
}

export default connect(mapStateToProps)(ProfileScreen);
...