Home > Blockchain >  "Objects are not valid as a React child" react error
"Objects are not valid as a React child" react error

Time:01-17

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 elements to be rendered by the Display component. Each element includes the component which receives two props (firstName and age) i still 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">
            {records.map(elem => {
                let fn = elem.firstName;
                let ageee = elem.age;
                return <li><SingleRecord firstName={fn} age={ageee} /></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');
    });


CodePudding user response:

SingleRecord = (firstName, age) should be SingleRecord = ({ firstName, age })

Props aren't passed as individual arguments, they're all in the first argument as an object. Trying to render {firstName} is causing you to try to render the entire props object, and the react error React is telling you that's an issue.

And you aren't using the LI variable. And did you read the error? Get in the habit of always reading errors, don't ignore them.

  • Related