I am using react-firebase-hooks https://github.com/CSFrequency/react-firebase-hooks/tree/v4.0.2/database#full-example
Below is values return when I console.log(v.val()) and when I do console.log(v.val().name) it's undefined.
{
1: { id: 1, name: "bob", status: "student" }
2: { id: 2, name: "sam", status: "student" }
}
When I try to render above data. I get the error Objects are not valid as a React child. If you meant to render a collection of children use an array instead.
import { ref, getDatabase } from 'firebase/database';
import { useList } from 'react-firebase-hooks/database';
const database = getDatabase(firebaseApp);
const DatabaseList = () => {
const [snapshots, loading, error] = useList(ref(database, 'list'));
return (
<div>
<p>
{error && <strong>Error: {error}</strong>}
{loading && <span>List: Loading...</span>}
{!loading && snapshots && (
<React.Fragment>
<span>
List:{' '}
{snapshots.map((v) => (
<React.Fragment key={v.key}>{v.val()}, </React.Fragment>
))}
</span>
</React.Fragment>
)}
</p>
</div>
);
};
How do I render my data correctly?
CodePudding user response:
That is because v.val()
is an object of objects, and as you are interested in the name
, you need to get the values of the first object and then map through it and hence access the name
.
import { ref, getDatabase } from 'firebase/database';
import { useList } from 'react-firebase-hooks/database';
const database = getDatabase(firebaseApp);
const DatabaseList = () => {
const [snapshots, loading, error] = useList(ref(database, 'list'));
return (
<div>
<p>
{error && <strong>Error: {error}</strong>}
{loading && <span>List: Loading...</span>}
{!loading && snapshots && (
<span>
List:{' '}
{snapshots.map((v,i) => (
Object.values(v.val()).map((obj,j) =>
<span key={i j}>{obj.name}, </span>
)
))}
</span>
)}
</p>
</div>
);
};