I try to get firestore database and dispatch this database in redux. and print this database in my listpage. I succeed to get firestore database, and console.log are print all data. but I try to use map() function. print only one data. I don't know why this had happened. I think my code is wrong. but I don't know where I got it wrong.
DictCard.js
import { collection, getDocs} from "firebase/firestore";
import React, { useEffect } from "react";
import { db } from "../firebase";
import { useSelector, useDispatch } from "react-redux";
import { getDict } from "../redux/ListReducer";
const Card = ({dict}) => {
return(
<div className="inbox">
<p className="text1">단어</p>
<p className="text2">{dict.word}</p>
<p className="text1">설명</p>
<p className="text2">{dict.explain}</p>
<p className="text1">예시</p>
<p className="text2" style={{color:"lightskyblue",paddingBottom:"0"}}>{dict.example}</p>
</div>
)
}
const DictCard = () => {
const dictList = useSelector((state) => state.dictList.dicts);
const dispatch = useDispatch();
useEffect( async () => {
const query = await getDocs(collection(db, "dict"));
query.forEach(doc => {
console.log([doc.id, doc.data()])
dispatch(getDict([{id: doc.id, text: doc.data()}]))
});
},[]);
return(
<div className="dict-card" >
{dictList.map((dict) => (
<Card dict = {dict.text} key = {dict.id}/>
))}
</div>
)
}
export default DictCard;
ListReducer.js
import { createSlice } from "@reduxjs/toolkit";
// const initialState = [{id:"",text:{word:"",explain:"",example:""}}]
const initState = {
dicts: [{
id:"",
text:{
word:"",
explain:"",
example:""
}
},]
}
export const ListReducer = createSlice({
name: "dictList",
initialState: initState,
reducers: {
addDict: (state, action) => {
state.dicts = action.payload
},
getDict: (state, action) => {
state.dicts = action.payload
},
updateDict: (state, action) => {
},
deleteDict: (state, action) => {
},
},
});
export const { addDict, getDict, updateDict, deleteDict } = ListReducer.actions;
export default ListReducer.reducer;
I think dispatch's position is wrong but i have no idea
CodePudding user response:
I solved problem.
useEffect( async () => {
const arr = []
const query = await getDocs(collection(db, "dict"));
query.forEach(doc => {
console.log([doc.id, doc.data()])
// dispatch(getDict([{id: doc.id, text: doc.data()}]))
arr.push({id: doc.id, text: doc.data()})
});
dispatch(getDict(arr))
},[]);
need to make empty array
CodePudding user response:
Try not to use async function
for useEffect
useEffect(() => { const fetchData = async () => { const query = await getDocs(collection(db, "dict")); query.forEach(doc => { console.log([doc.id, doc.data()]) dispatch(getDict([{id: doc.id, text: doc.data()}])) }); } fetchData() },[]);
I think the issue may caused from the useEffect
function. If it not, please comment below so i can track the issue more clearly