Variable not populating
Unanswered
Chinese perch posted this in #help-forum
Chinese perchOP
I've tried a whole bunch of things now.
page.tsx - this page needs to display the db data
page.tsx - this page needs to display the db data
'use client'
import Box from '@mui/material/Box';
import { DataGrid } from '@mui/x-data-grid';
import * as React from 'react';
import { MultipleSelectChip as Chip } from './components/ChipSelect';
import { useDataFetching } from './components/getClassData';
const rows = [
{
id: 1,
subject: 'Maths',
topic: 'Logs',
hw: 'Q123',
dd: '05-11-2023'
},
];
interface Student {
First_name: string;
}
export default function Home() {
const { data, loading, error } = useDataFetching(9, 'A');
if (loading) {
return <div>Loading...</div>;
}
if (error) {
return <div>Error: {error.message}</div>;
}
return (
<Box mt={1}>
<Chip names={data.map((student: { [x: string]: string; }) => {
student['First_name'] + " " + student['Last_name']
})}></Chip>
<DataGrid
columns={[
{
field: 'subject',
headerName: 'Subject',
description: 'The subject studied.',
editable: true
},
{ field: 'topic', headerName: 'Topic', description: 'The topic studied in the subject.', editable: true },
{ field: 'hw', headerName: 'Homework', description: 'Homework for the subject.', editable: true },
{
field: 'dd', headerName: 'Due date', description: 'The date the homework is due', editable: true, type: 'date',
valueFormatter: params => new Date(params?.value).toLocaleDateString(), flex: 1
},
]}
rows={rows}
/>
</Box>
)
}5 Replies
Chinese perchOP
connectTodb - connects to the db
'use server'
import mysql2 from 'mysql2'
export default async function connectTodb(StudentGrade: number, StudentSection: string) {
const db = mysql2.createConnection({
host: "",
user: "",
password: "",
database: ""
});
const [rows, fields] = await db.promise().query("SELECT First_name, Last_name, Grade, Section FROM student_list WHERE Grade=? AND Section=? ", [StudentGrade, StudentSection]);
return rows
}getClassData - calls the connect function to get the data. I was researching around and one site said the call also needs to be on the server
import connectTodb from './connectTodb';
import { useState, useEffect } from 'react';
export function useDataFetching(StudentGrade: number, StudentSection: string) {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
async function fetchData() {
try {
const result = await connectTodb(StudentGrade, StudentSection);
console.log(result)
setData(result);
setLoading(false);
} catch (error) {
setError(error);
setLoading(false);
}
}
fetchData();
}, [StudentGrade, StudentSection]);
return { data, loading, error };
}exact error
Chinese perchOP
bumpppppp