React 添加文档到 Firestore

huangapple go评论71阅读模式
英文:

React add document firestore

问题

以下是你提供的代码的翻译部分:

Hi I have a problem on code below I can't add a firestore collection to a db, when the setDoc line is executed it doesn't add the document to the collection, and the strange thing is that it doesn't print anything console, I'm using react, even though I use the add doc it does the same thing, the app is already connected to firebase because I logged in so the parameters are correct, what can it be?

**FirebaseFile.js**

import { initializeApp } from 'firebase/app';
import { getFirestore } from 'firebase/firestore';

var firebaseConfig = {
  ...
};

// Initialize Firebase
var app = initializeApp(firebaseConfig);
export const db = getFirestore(app);

**Another.js**

import React, { useRef, useState } from 'react';
import { doc, setDoc, collection } from 'firebase/firestore';

import styled from 'styled-components';
import EmailEditor from '../../../src';
import sample from './sample.json';
import sample2 from './sample2.json';
import sample3 from './sample3.json';
import { db } from '../firebase';
import Checkbox from '@mui/material/Checkbox';
import axios from 'axios';
const label = { inputProps: { 'aria-label': 'Checkbox demo' } };

const Container = styled.div`
  display: flex;
  flex-direction: column;
  position: relative;
  height: 100%;
`;

const Bar = styled.div`
  flex: 1;
  background-color: #000000;
  color: #000;
  padding: 10px;
  display: flex;
  max-height: 40px;

  h1 {
    flex: 1;
    font-size: 16px;
    text-align: left;
  }

  button {
    flex: 1;
    padding: 10px;
    margin-left: 10px;
    font-size: 14px;
    font-weight: bold;
    background-color: #000;
    color: #fff;
    border: 0px;
    max-width: 150px;
    cursor: pointer;
  }
`;

const Example = () => {
  const emailEditorRef = useRef(null);
  const [titolo, setTitolo] = useState('');
  const [newsProfileValue, setNewsProfileSet] = useState('');
  const [profileList, setNewsProfileList] = useState([]);
  const [premiumValue, setPremium] = useState(false);
  const [publicValue, setPublic] = useState(false);
  const arr = [];

  const saveDesign = () => {
    emailEditorRef.current.editor.saveDesign((design) => {
      exportData(design);
    });
  };

  const getList = async () => {
    try {
      //Recupero lo user id
      var id = await localStorage.getItem('uid');
      console.log(id);
      var data = [];
      const querySnapshot = await getDocs(collection(db, 'news_profiles'));
      querySnapshot.forEach((doc) => {
        if (doc.data().about.uid == id) {
          data.push({ title: doc.data().about.title, id: doc.id });
          arr.push({ doc: doc.data().about.title, id: doc.id });
        }
      });
    } catch (error) {
      console.log('Error: ' + error);
    }
    var options = arr.map((e) => {
      return `<option value="${e.id}">${e.doc}</option>`;
    });
    document.getElementById('selectNumber').innerHTML = options;
    setNewsProfileList(data);
  };

  const exportData = (design) => {
    const jsonString = `data:text/json;chatset=utf-8,${encodeURIComponent(
      JSON.stringify(design)
    )}`;
    const link = document.createElement('a');
    link.href = jsonString;
    link.download = 'data.json';
    link.click();
  };
  const exportHtml = () => {
    console.log('Sono in export html');
    addElementToFireStoreNews('prova');
    emailEditorRef.current.editor.exportHtml((data) => {
      const { design, html } = data;
      console.log('Sono dentor export');
      addElementToFireStoreNews(html);
      console.log("Sono dentor l'export");
    });
  };

  const addElementToFireStoreNewsAWS = async (html) => {
    var jsonFile;
    var templateid = await localStorage.getItem('templateid');
    if (templateid == 1) {
      jsonFile = sample;
    } else if (templateid == 2) {
      jsonFile = sample3;
    } else {
      jsonFile = sample2;
    }
    //Salvo la newsletter su aws
    emailEditorRef.current.editor.exportHtml((data) => {
      const { design, html } = data;
      var dataValue = {
        internal: true,
        online: publicValue,
        premium: premiumValue,
        html: html,
        template: jsonFile,
        subject: html,
        email: uuid,
      };
      axios
        .post(
          `https://europe-west3-mindit-newsletter.cloudfunctions.net/newsCreate`,
          dataValue
        )
        .then((res) => {
          console.log(res.json());
        });
    });
  };
  const addElementToFireStoreNews = async (html) => {
    console.log("Sono nell'inserimento del html");
    try {
      //addElementToFireStoreNewsAWS(html);
      var uuid = await localStorage.getItem('uid');
      const value = {
        aboutNews: {
          email: newsProfileValue,
          html: html,
          internal: true,
          photo: '',
          title: titolo,
        },
        date: new Date(),
        id: uuid,
        measures: {
          impression: {
            total: 0,
          },
          views: {
            moth: 0,
            total: 0,
            week: 0,
          },
        },
        public: true,
        searchKey: '',
        premium: premiumValue,
      };

      const newCityRef = doc(collection(db, 'news'));
      await setDoc(newCityRef, value);
    } catch (err) {
      console.log('Errore inserimnento: ' + err);
    }
  };

  const onDesignLoad = (data) => {
    console.log('onDesignLoad', data);
  };

  const onLoad = async () => {
    getList();

    var templateid = await localStorage.getItem('templateid');
    if (templateid == 1) {
      emailEditorRef.current.editor.loadDesign(sample);
    } else if (templateid == 2) {
      emailEditorRef.current.editor.loadDesign(sample3);
    } else {
      emailEditorRef.current.editor.loadDesign(sample2);
    }
    emailEditorRef.current.editor.addEventListener(
      'design:loaded',
      onDesignLoad
    );
  };

  const onReady = () => {};

  const changeText = (text) => {
    setTitolo(text);
  };

  const clickValue = (e) => {
    setNewsProfileSet(e.target.value);
  };

  const changeValue = () => {
    setPremium(!premium);
  };
  const changeValuePublic = () => {
    setPublic(!publicValue);
  };

  return (


<details>
<summary>英文:</summary>

Hi I have a problem on code below I can&#39;t add a firestore collection to a db, when the setDoc line is executed it doesn&#39;t add the document to the collection, and the strange thing is that it doesn&#39;t print anything console, I&#39;m using react, even though I use the add doc it does the same thing, the app is already connected to firebase because I logged in so the parameters are correct, what can it be?


**FirebaseFile.js**

    import { initializeApp } from &#39;firebase/app&#39;;
    import { getFirestore } from &#39;firebase/firestore&#39;;
    
    var firebaseConfig = {
      ...
    };
    
    // Initialize Firebase
    var app = initializeApp(firebaseConfig);
    export const db = getFirestore(app);
    
**Another.js**

    import React, { useRef, useState } from &#39;react&#39;;
    import { doc, setDoc,collection } from &#39;firebase/firestore&#39;;
    
    import styled from &#39;styled-components&#39;;
    import EmailEditor from &#39;../../../src&#39;;
    import sample from &#39;./sample.json&#39;;
    import sample2 from &#39;./sample2.json&#39;;
    import sample3 from &#39;./sample3.json&#39;;
    import { db } from &#39;../firebase&#39;;
    import Checkbox from &#39;@mui/material/Checkbox&#39;;
    import axios from &#39;axios&#39;;
    const label = { inputProps: { &#39;aria-label&#39;: &#39;Checkbox demo&#39; } };
    
    const Container = styled.div`
      display: flex;
      flex-direction: column;
      position: relative;
      height: 100%;
    `;
    
    const Bar = styled.div`
      flex: 1;
      background-color: #000000;
      color: #000;
      padding: 10px;
      display: flex;
      max-height: 40px;
    
      h1 {
        flex: 1;
        font-size: 16px;
        text-align: left;
      }
    
      button {
        flex: 1;
        padding: 10px;
        margin-left: 10px;
        font-size: 14px;
        font-weight: bold;
        background-color: #000;
        color: #fff;
        border: 0px;
        max-width: 150px;
        cursor: pointer;
      }
    `;
    
    const Example = () =&gt; {
      const emailEditorRef = useRef(null);
      const [titolo, setTitolo] = useState(&#39;&#39;);
      const [newsProfileValue, setNewsProfileSet] = useState(&#39;&#39;);
      const [profileList, setNewsProfileList] = useState([]);
      const [premiumValue, setPremium] = useState(false);
      const [publicValue, setPublic] = useState(false);
      const arr = [];
    
      const saveDesign = () =&gt; {
        emailEditorRef.current.editor.saveDesign((design) =&gt; {
          exportData(design);
        });
      };
    
      const getList = async () =&gt; {
        try {
          //Recupero lo user id
          var id = await localStorage.getItem(&#39;uid&#39;);
          console.log(id);
          var data = [];
          const querySnapshot = await getDocs(collection(db, &#39;news_profiles&#39;));
          querySnapshot.forEach((doc) =&gt; {
            if (doc.data().about.uid == id) {
              data.push({ title: doc.data().about.title, id: doc.id });
              arr.push({ doc: doc.data().about.title, id: doc.id });
            }
          });
        } catch (error) {
          console.log(&#39;Error: &#39; + error);
        }
        var options = arr.map((e) =&gt; {
          return `&lt;option value=&quot;${e.id}&quot;&gt;${e.doc}&lt;/option&gt;`;
        });
        document.getElementById(&#39;selectNumber&#39;).innerHTML = options;
        setNewsProfileList(data);
      };
    
      const exportData = (design) =&gt; {
        const jsonString = `data:text/json;chatset=utf-8,${encodeURIComponent(
          JSON.stringify(design)
        )}`;
        const link = document.createElement(&#39;a&#39;);
        link.href = jsonString;
        link.download = &#39;data.json&#39;;
        link.click();
      };
      const exportHtml = () =&gt; {
        console.log(&#39;Sono in export html&#39;);
        addElementToFireStoreNews(&#39;prova&#39;);
        emailEditorRef.current.editor.exportHtml((data) =&gt; {
          const { design, html } = data;
          console.log(&#39;Sono dentor export&#39;);
          addElementToFireStoreNews(html);
          console.log(&quot;Sono dentor l&#39;export&quot;);
        });
      };
    
      const addElementToFireStoreNewsAWS = async (html) =&gt; {
        var jsonFile;
        var templateid = await localStorage.getItem(&#39;templateid&#39;);
        if (templateid == 1) {
          jsonFile = sample;
        } else if (templateid == 2) {
          jsonFile = sample3;
        } else {
          jsonFile = sample2;
        }
        //Salvo la newsletter su aws
        emailEditorRef.current.editor.exportHtml((data) =&gt; {
          const { design, html } = data;
          var dataValue = {
            internal: true,
            online: publicValue,
            premium: premiumValue,
            html: html,
            template: jsonFile,
            subject: html,
            email: uuid,
          };
          axios
            .post(
              `https://europe-west3-mindit-newsletter.cloudfunctions.net/newsCreate`,
              dataValue
            )
            .then((res) =&gt; {
              console.log(res.json());
            });
        });
      };
      const addElementToFireStoreNews = async (html) =&gt; {
        console.log(&quot;Sono nell&#39;inserimento del html&quot;);
        try {
          //addElementToFireStoreNewsAWS(html);
          var uuid = await localStorage.getItem(&#39;uid&#39;);
          const value = {
            aboutNews: {
              email: newsProfileValue,
              html: html,
              internal: true,
              photo: &#39;&#39;,
              title: titolo,
            },
            date: new Date(),
            id: uuid,
            measures: {
              impression: {
                total: 0,
              },
              views: {
                moth: 0,
                total: 0,
                week: 0,
              },
            },
            public: true,
            searchKey: &#39;&#39;,
            premium: premiumValue,
          };
    
          const newCityRef = doc(collection(db, &#39;news&#39;));
          await setDoc(newCityRef, value);
        } catch (err) {
          console.log(&#39;Errore inserimnento: &#39; + err);
        }
      };
    
      const onDesignLoad = (data) =&gt; {
        console.log(&#39;onDesignLoad&#39;, data);
      };
    
      const onLoad = async () =&gt; {
        getList();
    
        var templateid = await localStorage.getItem(&#39;templateid&#39;);
        if (templateid == 1) {
          emailEditorRef.current.editor.loadDesign(sample);
        } else if (templateid == 2) {
          emailEditorRef.current.editor.loadDesign(sample3);
        } else {
          emailEditorRef.current.editor.loadDesign(sample2);
        }
        emailEditorRef.current.editor.addEventListener(
          &#39;design:loaded&#39;,
          onDesignLoad
        );
      };
    
      const onReady = () =&gt; {};
    
      const changeText = (text) =&gt; {
        setTitolo(text);
      };
    
      const clickValue = (e) =&gt; {
        setNewsProfileSet(e.target.value);
      };
    
      const changeValue = () =&gt; {
        setPremium(!premium);
      };
      const changeValuePublic = () =&gt; {
        setPublic(!publicValue);
      };
    
      return (
        &lt;Container&gt;
          &lt;Bar&gt;
            &lt;img src=&quot;firebase.png&quot; width=&quot;100&quot; height=&quot;50&quot; /&gt;
            &lt;label style={{ color: &#39;white&#39; }}&gt;
              &lt;b&gt;Titolo News: &lt;/b&gt;
              &lt;input
                type=&quot;text&quot;
                name=&quot;name&quot;
                onChange={(value) =&gt; changeText(value.target.value)}
                style={{ marginRight: 200 }}
              /&gt;
              Premium:{&#39; &#39;}
              &lt;Checkbox
                {...label}
                unchecked
                onClick={() =&gt; changeValue()}
                style={{ color: &#39;white&#39; }}
              /&gt;
              Online:{&#39; &#39;}
              &lt;Checkbox
                {...label}
                unchecked
                onClick={() =&gt; changeValuePublic()}
                style={{ color: &#39;white&#39; }}
              /&gt;
            &lt;/label&gt;
            &lt;form id=&quot;myForm&quot;&gt;
              &lt;select id=&quot;selectNumber&quot; onClick={clickValue}&gt;
                &lt;option&gt;Scegli il news profile&lt;/option&gt;
              &lt;/select&gt;
              &lt;button onClick={() =&gt; saveDesign}&gt; Salva Design &lt;/button&gt;
              &lt;button onClick={() =&gt; addElementToFireStoreNews(&#39;prova&#39;)}&gt;
                {&#39; &#39;}
                Salva Articolo{&#39; &#39;}
              &lt;/button&gt;{&#39; &#39;}
            &lt;/form&gt;
          &lt;/Bar&gt;
          &lt;React.StrictMode&gt;
            &lt;EmailEditor ref={emailEditorRef} onLoad={onLoad} onReady={onReady} /&gt;{&#39; &#39;}
          &lt;/React.StrictMode&gt;{&#39; &#39;}
        &lt;/Container&gt;
      );
    };
    
    export default Example;



</details>


# 答案1
**得分**: 1

这似乎是你合并了两个文件但将其列为一个文件如果这是一个文件那么导入`db`两次将会有问题

```javascript
import { initializeApp } from 'firebase/app';
import { getFirestore } from 'firebase/firestore';

var firebaseConfig = {
  ...
};

// 初始化 Firebase
var app = initializeApp(firebaseConfig);
export const db = getFirestore(app); &lt;-------- 使用这个。

import React, { useRef, useState } from 'react';
import { doc, setDoc, collection } from 'firebase/firestore';

import styled from 'styled-components';
import EmailEditor from '../../../src';
import sample from './sample.json';
import sample2 from './sample2.json';
import sample3 from './sample3.json';
import { db } from '../firebase'; &lt;----- 这是什么?

否则,如果你在本地遇到问题,请确保你启动了本地的`Firestore Emulator`,否则你可能会更新你的实时 Firestore 实例。

// 检测开发环境
connectFirestoreEmulator(db, '127.0.0.1', 6060);
英文:

It seems like you merged two files but you listed this as one file. If that's one file, then you are importing db twice which would be a problem:

import { initializeApp } from &#39;firebase/app&#39;;
import { getFirestore } from &#39;firebase/firestore&#39;;
var firebaseConfig = {
...
};
// Initialize Firebase
var app = initializeApp(firebaseConfig);
export const db = getFirestore(app); &lt;-------- Use this.
import React, { useRef, useState } from &#39;react&#39;;
import { doc, setDoc,collection } from &#39;firebase/firestore&#39;;
import styled from &#39;styled-components&#39;;
import EmailEditor from &#39;../../../src&#39;;
import sample from &#39;./sample.json&#39;;
import sample2 from &#39;./sample2.json&#39;;
import sample3 from &#39;./sample3.json&#39;;
import { db } from &#39;../firebase&#39;; &lt;----- What is this?

Otherwise, if you are having the problem locally, make sure you are starting your local Firestore Emulator or else you'll probably be updating your live Firestore instance.

// detect for development ENV
connectFirestoreEmulator(db, &#39;127.0.0.1&#39;, 6060);

huangapple
  • 本文由 发表于 2023年2月10日 04:53:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/75404323.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定