I keep getting this error
TypeError: Cannot read property 'useState' of null
whenever I try pulling data from the firestore database. The error points to when I am using the useState and this is how my code looks like
import React from 'react'
import { useState } from 'react';
import { db } from '../firebaseconfig'
import { collection, getDocs } from "firebase/firestore";
const reference = collection(db, "students");
const [students, setstudents] = useState([]);
export const getStaticProps = async () => {
const data = await getDocs(reference);
setstudents(data.docs.map(doc => ({...doc.data(), id: doc.id})));
return {
props: students
}
}
function Card({students}) {
return (
<div>
{students.map(student => (
<h1>{student.name}</h1>
))}
</div>
)
}
export default Card
Where could I be going wrong?
CodePudding user response:
you are using 2 react imports. Make it one
try this:
import React, { useState} from 'react'
CodePudding user response:
In the code snippet you have provided, the state students
does not have any other purpose than being sent as props to Card component.
Based on the nextjs docs (https://nextjs.org/docs/basic-features/data-fetching/get-static-props#using-getstaticprops-to-fetch-data-from-a-cms) , modify the code like this and try
import React from 'react'
import { db } from '../firebaseconfig'
import { collection, getDocs } from "firebase/firestore";
const reference = collection(db, "students");
export const getStaticProps = async () => {
const data = await getDocs(reference);
const students=data.docs.map(doc => ({...doc.data(), id: doc.id}));
return {
props: {
students
}
}
}
function Card({students=[]}) {
return (
<div>
{students.map(student => (
<h1>{student.name}</h1>
))}
</div>
)
}
export default Card