Home > Enterprise >  React/FireStore : Error: Objects are not valid as a React child
React/FireStore : Error: Objects are not valid as a React child

Time:03-13

To train myself i'm currently creating a social media with react and firebase and i'm getting this error i can't resolve despise searching for answer here :

Uncaught Error: Objects are not valid as a React child (found: object with keys {message, user}). If you meant to render a collection of children, use an array instead.

To be clear, a "mood" can be viewed such as a facebook or status or an instagram post.

here's my code :

Firebase.js

import firebase from 'firebase/compat/app';
import 'firebase/compat/auth';
import 'firebase/compat/firestore';

const firebaseConfig = {
    apiKey: "***************************",
    authDomain: "*******.firebaseapp.com",
    projectId: "********",
    storageBucket: "**************",
    messagingSenderId: "**************",
    appId: "*****************************************"
};

const firebaseApp = firebase.initializeApp(firebaseConfig);

const db = firebaseApp.firestore();
const auth = firebase.auth();

export { auth, db };

Home.js

import React, { useState, useEffect } from 'react'
import Header from '../shared/header/Header'
import Mood from '../shared/mood/Mood';
import './Home.css'
import { doc, onSnapshot } from "firebase/firestore";
import { db } from '../../services/firebase';

function Home() {

  const [moods, setMoods] = useState([]);

  useEffect(() => {
    db.collection("mood").onSnapshot((querySnapshot) =>
      setMoods(
        querySnapshot.docs.map((doc) => ({
          id: doc.id,
          data: doc.data()
        }))
      ));
    console.log(moods);
  }, []);

  return (
    <div className='home'>
      <Header />
      <div className='feed'>
        {moods.map(({id, data: {message, user}}) => (
            <Mood 
            key={id}
            message={message}
            user={user}
            />
          ))}
      </div>
    </div>
  )
}

export default Home

Mood.js

import React from 'react'
import './Mood.css'

function Mood(id, message, user) {
  return (
    <div className='mood'>
        <h4>{id}</h4>
        <h5>{user}</h5>
        <p>{message}</p>
    </div>
  )
}

export default Mood

and don't hesitate to point out my react practice if you feel like it :)

thanks in advance guys!

CodePudding user response:

You just need to destructure the props in Mood component like this, and also you need to add another prop id={id} in home component

function Mood({id, message, user}) {
  return (
    <div className='mood'>
        <h4>{id}</h4>
        <h5>{user}</h5>
        <p>{message}</p>
    </div>
  )
}

and another thing i can see is bad is in Home return statement when you are destructuring, do this instead {id, {message, user}}

  • Related