Im writing a function that gets the active (selected) organisation.
Getting the values from the database was easy, making typescript happy is still a struggle.
const { data, error } = await supabase
.from('profiles')
.select('active_organisation, organisations:organisations (*)')
.eq('id', user.id)
.single();
In this query i get a few things, the active organisation which is a number, but i also get the organisation with all its columns that is linked to my user.
How my code is setup, that linked organisation can only be one, so there is no way that organisations could be multiple rows.
**Now here comes the problem im facing:
**
Typescript thinks that organisations is an array and when i try to declare a type for the single row, it says i need to make sure its an array type because it might me multiple rows.
This is my full function for a bit more context.
Here you can see that in my return succes i try to make sure that organisations gets the type Organisation, but typescript wants me to use the following type Organisation[]
export async function getActiveOrganisation() {
const supabase = await createClient();
const { data: userData, error: userError } = await supabase.auth.getUser();
if (userError || !userData.user) {
return { success: false, error: 'User not found' };
}
const user = userData.user;
const { data, error } = await supabase
.from('profiles')
.select('active_organisation, organisations:organisations (*)')
.eq('id', user.id)
.single();
if (error) {
return { success: false, error: error.message };
}
if (!data) {
return { success: false, error: 'No profile found for the user' };
}
console.log(data);
const organisation = data.organisations;
if (!organisation) {
return { success: false, error: 'No organisation found for the user' };
}
return { success: true, organisations: organisation as Organisation, activeOrganisationId: data.active_organisation };
}
Id love to learn from a mistake i might have made, or something i dont know yet.
Also if there are any tips related to my way of coding they are more than welcome.