0

the data is not displayed by REACT and the following error is received: "Objects are not valid as a React child. If you meant to render a collection of children, use an array instead"

The records from MongoDB collection are fetched and gathered in an array of objects. then I use the .map() function to produce the array of

  • elemens to be rendered by the Display component. Each
  • element includes the component which receives two props (firstName and age)

    i do not see where is my mistake...

    thanx for help!

    SingleRecord.js:

        const SingleRecord = (firstName, age) => {    
            return (
            <li className="singe-record">
                {firstName} is {age} years old.
            </li>
            );
        }
        
        export default SingleRecord;
    

    Display.js:

        function Display() {
            const [records, setRecords] = useState();
            const dataArray = [];
    
            const fetchRecords = () => {
                fetch('http://localhost:3001/users')
                .then(async response => {
                    const isJson = await response.headers.get('content-type')?.includes('application/json');           
                    const data = isJson ? await response.json() : null;
    
                for (const elem of data) {
                let elemObj = {
                    _id: elem._id, 
                    firstName: elem.firstName,
                    age: elem.age};
                    dataArray.push(elemObj);
                }
                    setRecords(dataArray);
    
                    // check for error response
                if (!response.ok) {
                        // get error message from body or default to response status
                const error = (data && data.message) || response.status;
                return Promise.reject(error);
                }
                })
                .catch(error => {
                    console.error('There was an error!', error);
                });
            }
    
            useEffect(() => {  
                fetchRecords();
                // eslint-disable-next-line react-hooks/exhaustive-deps
            }, []);
    
            if (!records) {
                return null;
            }
    
            const LI = records.map(elem => {
                        let fn = elem.firstName;
                        let ageee = elem.age;
                        return <li><SingleRecord firstName={fn} age={ageee} /></li>
            })
    
            return (
                <div className="records-display">
                <h2>Records:</h2>
                <ul className ="records-list">
                    {LI}
                </ul>      
                </div>
            );
        }
    

    app.js (backend):

        const { MongoClient } = require("mongodb");
        const uri = "...hidden...";
        const client = new MongoClient(uri);
        const database = client.db('holdocsDB');
        const records = database.collection('records');
    
        app.get('/users', async (req, res) => {
            const cursor = await records.find();  
            const results = await cursor.toArray();
            res.send(results);         
        })
            
        // catch 404 and forward to error handler
        app.use(function(req, res, next) {
            next(createError(404));
        });
        
        // error handler
        app.use(function(err, req, res, next) {
            // set locals, only providing error in development
            res.locals.message = err.message;
            res.locals.error = req.app.get('env') === 'development' ? err : {};
    
            // render the error page
            res.status(err.status || 500);
            res.json('error');
        });
    
    
    
  • Toto
    • 13
    • 3

    1 Answers1

    0

    Its because LI is an array, so you would get the same error if you did something like:

    {['foo', 'bar']}

    change it to this and give it a try:

        return (
            <div className="records-display">
            <h2>Records:</h2>
            <ul className ="records-list">
                {records.map(elem => {
                    let fn = elem.firstName;
                    let ageee = elem.age;
                    return <li><SingleRecord firstName={fn} age={ageee} /></li>
                 })}
            </ul>      
            </div>
        );
    
    terpinmd
    • 1,014
    • 8
    • 15
    • thanx for your response, @terpinmd! unfortunately it still doesn't work and I get the same error after making the changes that you proposed – Toto Jan 16 '23 at 16:42
    • 1
      solved! in SingleRecord.js component code instead of passing the literal values as arguments, I had to pass "(props)" and use the props as 'props.firstName' and 'props.age'. – Toto Jan 16 '23 at 17:29