英文:
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'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 (
<Container>
<Bar>
<img src="firebase.png" width="100" height="50" />
<label style={{ color: 'white' }}>
<b>Titolo News: </b>
<input
type="text"
name="name"
onChange={(value) => changeText(value.target.value)}
style={{ marginRight: 200 }}
/>
Premium:{' '}
<Checkbox
{...label}
unchecked
onClick={() => changeValue()}
style={{ color: 'white' }}
/>
Online:{' '}
<Checkbox
{...label}
unchecked
onClick={() => changeValuePublic()}
style={{ color: 'white' }}
/>
</label>
<form id="myForm">
<select id="selectNumber" onClick={clickValue}>
<option>Scegli il news profile</option>
</select>
<button onClick={() => saveDesign}> Salva Design </button>
<button onClick={() => addElementToFireStoreNews('prova')}>
{' '}
Salva Articolo{' '}
</button>{' '}
</form>
</Bar>
<React.StrictMode>
<EmailEditor ref={emailEditorRef} onLoad={onLoad} onReady={onReady} />{' '}
</React.StrictMode>{' '}
</Container>
);
};
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); <-------- 使用这个。
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'; <----- 这是什么?
否则,如果你在本地遇到问题,请确保你启动了本地的`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 'firebase/app';
import { getFirestore } from 'firebase/firestore';
var firebaseConfig = {
...
};
// Initialize Firebase
var app = initializeApp(firebaseConfig);
export const db = getFirestore(app); <-------- Use this.
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'; <----- 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, '127.0.0.1', 6060);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论