简体   繁体   English

如何将 firebase 添加到我的反应项目中?

[英]How do I add firebase to my react project?

I found an article on Medium which uses React and Firebase for a Todolist application.我在 Medium 上找到了一篇文章,它使用 React 和 Firebase 作为 Todolist 应用程序。 Following the instructions on the article, I installed all the needed dependancies, created the React app and copy pasted in the code.按照文章中的说明,我安装了所有需要的依赖项,创建了 React 应用程序并复制粘贴到代码中。 I then also went to Firebase and added in a collection as specified in the article https://medium.com/@sarahzhan/building-a-todo-app-with-crud-operations-using-firebase-react-hooks-and-material-ui-caf4b1f2ecbc .然后我也去了 Firebase 并添加到文章https 中指定的集合中://medium.com/@sarahzhan/building-a-todo-app-with-crud-operations-using-firebase-react-hooks-and -材料用户界面-caf4b1f2ecbc However, when I run the development server I get an error saying:但是,当我运行开发服务器时,我收到一条错误消息:

./src/App.js
Module not found: Can't resolve 'firebase' in {folder-name}

So my question is, how do I fix this, and what am I doing wrong?所以我的问题是,我该如何解决这个问题,我做错了什么?

This is the code, in case it helps:这是代码,以防它有帮助:

firebase.js firebase.js

import firebase from "firebase";

    const firebaseApp = firebase.initializeApp({
      apiKey: "xxxxxxxxxxxxxxxxxxxxxxx",
      authDomain: "xxxxxxxxxxxxxxxxxxx",
      projectId: "xxxxxxxxxxxxxxxxxxx",
      storageBucket: "xxxxxxxxxxxxxxxxx",
      messagingSenderId: "xxxxxxxxxxxxxx",
      appId: "xxxxxxxxxxxxxxxxxxx",
    });
    
    const db = firebaseApp.firestore();
    
    export default db;

App.js应用程序.js

import React, { useState, useEffect } from "react";
import {
  Button,
  FormControl,
  InputLabel,
  Input,
  FormHelperText,
} from "@material-ui/core";
import firebase from "firebase";

import Todo from "./Todo";
import db from "./firebase";

function App() {
  const [todos, setTodos] = useState([]);
  const [input, setInput] = useState("");

  // when the app loads, we need to listen to firebase
  // fetch new todos as they get added/removed
  useEffect(() => {
    // this fires when the app.js loads
    // everytime the db changes, it snaps it and give you that snapshot
    db.collection("todos")
      .orderBy("timestamp", "desc")
      .onSnapshot((snapshot) => {
        // this gives back an array
        setTodos(
          snapshot.docs.map((doc) => ({
            id: doc.id,
            todo: doc.data().todo,
          }))
        );
      });
  }, []);

  const addTodo = (event) => {
    event.preventDefault();

    db.collection("todos").add({
      todo: input,
      timestamp: firebase.firestore.FieldValue.serverTimestamp(),
    });
    // empty input after the todo is successfully stored in firebase
    setInput("");
  };

  return (
    <div className="App">
      <h1>Hello World!!!</h1>
      <form>
        <FormControl>
          <InputLabel>
            <span role="img" aria-label="emoji">
              ✅
            </span>
            Write a Todo
          </InputLabel>
          <Input value={input} onChange={(e) => setInput(e.target.value)} />
          <FormHelperText>We'll make you productive</FormHelperText>
        </FormControl>

        <Button
          disabled={!input}
          type="submit"
          variant="contained"
          color="primary"
          onClick={addTodo}
        >
          Add Todo
        </Button>
      </form>

      <ul>
        {todos.map((todo) => (
          <Todo todo={todo} />
        ))}
      </ul>
    </div>
  );
}

export default App;

Todo.js待办事项

import React, { useState } from "react";
import {
  List,
  ListItem,
  ListItemText,
  ListItemAvatar,
  Button,
  Modal,
} from "@material-ui/core";
import { makeStyles } from "@material-ui/core/styles";
// import "./Todo.css";

import db from "./firebase";

const useStyles = makeStyles((theme) => ({
  paper: {
    position: "relative",
    left: 400,
    width: 600,
    backgroundColor: theme.palette.background.paper,
    boxShadow: theme.shadows[5],
    padding: theme.spacing(2, 4, 3),
  },
  button: {
    width: 150,
    margin: "10px",
  },
}));

const Todo = (props) => {
  const classes = useStyles();
  const [open, setOpen] = useState(false);
  const [input, setInput] = useState();

  const handleOpen = () => {
    setOpen(true);
  };

  const updateTodo = () => {
    db.collection("todos").doc(props.todo.id).set(
      {
        todo: input,
      },
      // prevents you to overwrite/remove it, instead update it
      { merge: true }
    );
    setOpen(false);
  };
  return (
    <>
      <Modal open={open} onClose={(e) => setOpen(false)}>
        <div className={classes.paper}>
          <h3>Update the Task</h3>
          <input
            placeholder={props.todo.todo}
            value={input}
            onChange={(e) => setInput(e.target.value)}
          />
          <Button
            variant="contained"
            color="default"
            onClick={updateTodo}
            className={classes.button}
          >
            Update ✔
          </Button>
        </div>
      </Modal>
      <List className="todo__list">
        <ListItem>
          <ListItemAvatar></ListItemAvatar>
          <ListItemText
            primary={props.todo.todo}
            secondary="Uploaded Task 🤞 "
          />
        </ListItem>

        <button onClick={(e) => setOpen(true)}>Edit</button>

        <Button
          onClick={(e) => db.collection("todos").doc(props.todo.id).delete()}
        >
          DELETE
        </Button>
      </List>
    </>
  );
};

export default Todo;

These are my dependancies.这些是我的依赖。

"dependencies": {
    "@material-ui/core": "^4.12.3",
    "@material-ui/icons": "^4.11.2",
    "@testing-library/jest-dom": "^5.14.1",
    "@testing-library/react": "^11.2.7",
    "@testing-library/user-event": "^12.8.3",
    "dotenv": "^10.0.0",
    "firebase": "^9.0.1",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-scripts": "4.0.3",
    "web-vitals": "^1.1.2"
  },

Any help would be extremely helpful.任何帮助都会非常有帮助。

You have to use new commands to add firebase in your application because of version change from firebase 8 to firebase 9.0 You can Find useful commands at their official site https://firebase.google.com/docs/web/modular-upgrade由于版本从firebase 8更改为firebase 9.0 ,您必须使用新命令在应用程序中添加firebase您可以在其官方网站https://firebase.google.com/docs/web/modular-upgrade找到有用的命令

Before: version 8之前:版本 8




import firebase from 'firebase/app';
import 'firebase/auth';
import 'firebase/firestore';


After: version 9 compat之后:版本 9 兼容

// v9 compat packages are API compatible with v8 code
import firebase from 'firebase/compat/app';
import 'firebase/compat/auth';
import 'firebase/compat/firestore';

Here is a small gist with a hook I made as an alternative to react-firebase-hooks, and hopefully it will be of use and if anyone wants to make suggestions I'm open to receiving them.这是我制作的一个带有钩子的小要点,作为 react-firebase-hooks 的替代品,希望它会有用,如果有人想提出建议,我愿意接受他们。

Nowadays you'll have to set via functions the collection and document references, instead of chaining from the firestore instance you create from your initialized app.现在,您必须通过函数设置集合和文档引用,而不是从您从初始化应用创建的 firestore 实例进行链接。

Pretty much here's a snippet:几乎这里有一个片段:

import { fs } from "../config/firebase"; // const fs = useFirestore() from the initializeApp config
import { collection, query, where, getDocs, limit, WhereFilterOp } from "firebase/firestore";

import useInterval from "./useInterval";

export interface IQuery {
  ref: string;
  operator: WhereFilterOp;
  value: any;
}

const useFirestore = (
  collectionString: string = "defaultCollection",
  limitNumber: number = 100,
  queryData?: IQuery
) => {
  const [data, setData] = useState<any[] | void>([]);

  // Instead of using the snapshot directly, im throttling the data updating to a second.
  useInterval(async () => {
    const result = await querySnapshot;
    setData(result);
  }, 1000);

  // Create a query against the collection.
  const q = queryData
    ? query(
        collection(fs, collectionString),
        where(queryData?.ref, queryData?.operator, queryData?.value),
        limit(limitNumber)
      )
    : query(collection(fs, collectionString), limit(limitNumber));

  const querySnapshot = getDocs(q)
    .then((snapshot) => {
      const data: any[] = snapshot.docs.map((doc) => {
        return {
          id: doc.id,
          ...doc.data(),
        };
      });
      return data;
    })
    .catch((error) => {
      console.error("Error getting documents: ", error);
    });

  return { data };
};

export default useFirestore;

And this is how you can call it:这就是你如何称呼它:

const { data: alias } = useFirestoreQuery("collection");
const { data: alias } = useFirestoreQuery("collection", 50 //limit);
const { data: alias } = useFirestoreQuery("collection", 10, {
ref: "location",
operator: "==",
value: name,
});

GIST 要旨

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我是否需要在我的 Firebase 项目中添加 SHA-1 指纹? - Do I need to add SHA-1 fingerprint in my Firebase project? 如何在 React 项目中设置 firebase 以连接到正确的 firebase 控制台帐户? - How do I set up firebase in a react project to connect to the right firebase console account? 如果我的后端是 firebase firestore,我如何在我的 react js 应用程序中使用 JWT - How do i use JWT in my react js app, if my backend is firebase firestore 如何将数据从我的数据库 (Firebase Firestore) 发送到我的 React Native 应用程序? - How do I send data from my database (Firebase Firestore) to my React Native app? 如何在我的 Android React Native 项目中安装 Firebase AppCheck? - How can I install Firebase AppCheck in my Android React Native project? 我希望使用复选框将成员添加到项目中 (Firebase React) - I wish to add members to a project using checkboxes (Firebase React) 如何在 React-native 中将我的 firebase v8 代码更新为 v9? - How do i update my firebase v8 code to v9 in React-native? 如何将新的 firebase 模拟器添加到我现有的项目中? - how to add new firebase emulators to my existing project? 如何将 a.then 添加到 firebase getDocs() - How do I add a .then to a firebase getDocs() 如何将 Object 添加到 Firebase RTDB - How do i add Object to Firebase RTDB
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM