简体   繁体   中英

How to read array document field from firebase firestore (React js)

Hi I am trying to get todo array field from cloud firestore database in a react project. When i print out with console log I can see the empty array symbol but It throws error at the same time and does not render the page.

在此处输入图像描述

This is the Firestore.js file to get data from firebase.

 export const userTodoList = async (email) => { await onSnapshot(doc(db, "users", email), (doc) => { console.log(doc.data().todos); return doc.data().todos; }); };

This the MainPage.js file to get the array and pass to CardList component.

 const MainPage = () => { const todoArray = userTodoList(auth.currentUser.email); const [todos, setTodos] = useState(todoArray); return ( <div> <section> <NavBar></NavBar> <ToDoForm /> </section> <section> <CardList array={todos} /> </section> </div> ); };

This is the CardList component to render the cards with the array mapping. I am checking for if the array length is 0 or not but still get errors.

 const CardList = (props) => { const array = props.array; if (array.length === 0) { return ( <div className="grid_container"> <h2>Found no todos</h2> </div> ); } return ( <div className="grid_container"> {array.map((todo) => ( <Card title={todo.title} /> ))} </div> ); };

Errors.

在此处输入图像描述 在此处输入图像描述

The object.map is not a function error occurs because the map method is not implemented on objects. To iterate over an object, use the Object.keys() method to get an array of the object's keys and call the map() method on the array of keys.

Ie You can use Object.keys() or Object.entries() and then use map

For example:

 array.keys(obj).map(key => { //other statements });

For more details you can check this article

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM