I am trying to get data from supabase database. However, I keep getting a null return for it even though it works fine in another route and match the id with employees in the database and I am sure that there is an employee with this id
import { useRouter } from 'next/router'
import { useState, useEffect } from 'react'
import { supabase } from '../../supabase';
import React from 'react'
export default function Id() {
const id = useRouter().query.id;
console.log(id)
const [data, setData] = useState([]);
const [error, setError] = useState(null);
useEffect(() => {
let cancelFetch = false; // to avoid race conditions on React18
supabase
.from("Employees")
.select("*")
.eq("id", id)
.then((res) => {
if (!cancelFetch) {
setData(res.data);
setError(res.error);
}
});
return () => {
cancelFetch = true;
};
}, []);
useEffect(() => {
console.log(data)
}, [data])
return (
<div>
{data.map( (index) => {
<h1>{index.name}</h1>
})}
</div>
)
}
CodePudding user response:
if you are getting the null from the console.log
add it inside the function,
for the return div
you can make an if statement to load the date after its load from the server:
<div>{ data ? data.name : "" }</div>
CodePudding user response:
It appears at there might be an issues with data structure. You are setting default state for data as an empty Array with const [data, setData] = useState([]);
but you are treating it as an object in your return <div>{data.name}</div>
I believe the database's response is going to come as an array of objects as in res.data = [{id: 0, name: 'John'}, {id: 1, name 'Jane'}, ...]
so in that case you'd need to map over the results or hardcode it as <div>{ data.length>0 ? data[0].name : 'no data bruh :(' }</div>
also, you're declaring const id = useRouter().query.id;
but you never use it in this snippet.
what comes from the console log if you use it in an useEffect?
useEffect(() => {
console.log('data: ', data)
},[data])