Home > front end >  How to read array document field from firebase firestore (React js)
How to read array document field from firebase firestore (React js)

Time:07-05

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.

enter image description here

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.

enter image description here enter image description here

CodePudding user response:

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.

I.e 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

  • Related