Skip to content

Commit

Permalink
allow user to click on plants, refactored backend requests
Browse files Browse the repository at this point in the history
  • Loading branch information
SashankBalusu committed Nov 12, 2024
1 parent d1a98e1 commit 09eee6d
Show file tree
Hide file tree
Showing 7 changed files with 167 additions and 45 deletions.
7 changes: 6 additions & 1 deletion api/supabase/queries/plants.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { UUID } from 'crypto';
import { Plant } from '@/types/schema';
import { Plant, UserPlants } from '@/types/schema';
import supabase from '../createClient';

export async function getAllPlants(): Promise<Plant[]> {
Expand All @@ -21,3 +21,8 @@ export async function getPlantById(plantId: UUID): Promise<Plant> {

return data;
}
export async function getMatchingPlantForUserPlants(
userPlant: UserPlants,
): Promise<Plant> {
return getPlantById(userPlant['plant_id']);
}
19 changes: 0 additions & 19 deletions api/supabase/queries/updateUserPlants.ts

This file was deleted.

46 changes: 46 additions & 0 deletions api/supabase/queries/userPlants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { UUID } from 'crypto';
import { UserPlants } from '@/types/schema';
import supabase from '../createClient';

export async function updateUserPlants(
userId: UUID,
formData: Partial<UserPlants>[],
) {
formData.map(async curr => {
const { error } = await supabase.from('user_plants').insert({
user_id: userId,
plant_id: curr['plant_id'],
date_added: curr['date_added'],
date_harvested: null,
planting_type: curr['planting_type'],
});
if (error) throw new Error(`Error inserting data: ${error.message}`);
});
}
export async function getUserPlantById(userPlantId: UUID): Promise<UserPlants> {
const { data, error } = await supabase
.from('user_plants')
.select('*')
.eq('id', userPlantId)
.is('date_harvested', null)
.limit(1)
.single();

if (error) {
throw new Error(`Error fetching plant ID: ${error}`);
}
return data;
}
export async function getUserPlantsByUserId(
user_id: UUID,
): Promise<UserPlants[]> {
const { data, error } = await supabase
.from('user_plants')
.select('*')
.eq('user_id', user_id)
.is('date_harvested', null);
if (error) {
throw new Error(`Error fetching userPlant: ${error}`);
}
return data;
}
2 changes: 1 addition & 1 deletion app/add-details/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { UUID } from 'crypto';
import { updateUserPlants } from '@/api/supabase/queries/updateUserPlants';
import { updateUserPlants } from '@/api/supabase/queries/userPlants';
import PlantDetails from '@/components/PlantDetails';
import { Plant, UserPlants } from '@/types/schema';

Expand Down
29 changes: 29 additions & 0 deletions app/all-plants/[plantId]/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
'use client';

import { useEffect, useState } from 'react';
import { useParams } from 'next/navigation';
import { UUID } from 'crypto';
import { getPlantById } from '@/api/supabase/queries/plants';
import { Plant } from '@/types/schema';

export default function GeneralPlantPage() {
const params = useParams();
const plantId: UUID = params.plantId as UUID;
const [currentPlant, setCurrentPlant] = useState<Plant>();
useEffect(() => {
const getPlant = async () => {
const plant = await getPlantById(plantId);
setCurrentPlant(plant);
};
getPlant();
}, [plantId]);
return (
<div>
{currentPlant && (
<div>
<h3>{JSON.stringify(currentPlant)}</h3>
</div>
)}
</div>
);
}
36 changes: 36 additions & 0 deletions app/my-plants/[userPlantId]/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
'use client';

import { useEffect, useState } from 'react';
import { useParams } from 'next/navigation';
import { UUID } from 'crypto';
import { getMatchingPlantForUserPlants } from '@/api/supabase/queries/plants';
import { getUserPlantById } from '@/api/supabase/queries/userPlants';
import { Plant, UserPlants } from '@/types/schema';

export default function UserPlantPage() {
const params = useParams();
const userPlantId: UUID = params.userPlantId as UUID;
const [currentPlant, setCurrentPlant] = useState<Plant>();
const [currentUserPlant, setCurrentUserPlant] = useState<UserPlants>();
useEffect(() => {
const getPlant = async () => {
const userPlant = await getUserPlantById(userPlantId);
setCurrentUserPlant(userPlant);
const plant = await getMatchingPlantForUserPlants(userPlant);
setCurrentPlant(plant);
// const plant = await getPlantById(await getUserPlantById(userPlantId))
// setCurrentPlant(plant)
};
getPlant();
}, [userPlantId]);
return (
<div>
{currentPlant && (
<div>
<h3>{JSON.stringify(currentUserPlant)}</h3>
<h3>{JSON.stringify(currentPlant)}</h3>
</div>
)}
</div>
);
}
73 changes: 49 additions & 24 deletions app/view-plants/page.tsx
Original file line number Diff line number Diff line change
@@ -1,21 +1,28 @@
'use client';

import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { UUID } from 'crypto';
import styled from 'styled-components';
import supabase from '@/api/supabase/createClient';
import { getAllPlants, getPlantById } from '@/api/supabase/queries/plants';
import {
getAllPlants,
getMatchingPlantForUserPlants,
} from '@/api/supabase/queries/plants';
import { getUserPlantsByUserId } from '@/api/supabase/queries/userPlants';
import PlantCard from '@/components/PlantCard';
import { Plant } from '@/types/schema';

export default function Page() {
const router = useRouter();
const [viewingOption, setViewingOption] = useState<'myPlants' | 'all'>(
'myPlants',
);
const [inAddMode, setInAddMode] = useState<boolean>(false);
const [plants, setPlants] = useState<Plant[]>([]);
const [userPlants, setUserPlants] = useState<Plant[]>([]);
const [selectedPlants, setSelectedPlants] = useState<Plant[]>([]);
const [ownedPlants, setOwnedPlants] = useState<Map<UUID, UUID>>();

const user_id: UUID = 'e72af66d-7aae-45f6-935a-187197749d9f';
const userState = 'TENNESSEE';

Expand All @@ -24,22 +31,18 @@ export default function Page() {
`;

async function fetchUserPlants(user_id: UUID) {
const { data, error } = await supabase
.from('user_plants')
.select('plant_id')
.eq('user_id', user_id)
.is('date_harvested', null);
const data = await getUserPlantsByUserId(user_id);

if (error) {
console.error('Error fetching plant IDs:', error);
return [];
}
if (!data) return [];
const plantIds = data.map(row => row.plant_id) || [];
data.map(row => {
setOwnedPlants(prevOwnedPlants =>
new Map(prevOwnedPlants).set(row.plant_id, row.id),
);
});

const plantsUser: Plant[] = await Promise.all(
plantIds.map(plantId => getPlantById(plantId)),
data.map(row => getMatchingPlantForUserPlants(row)),
);

return plantsUser;
}

Expand All @@ -61,11 +64,25 @@ export default function Page() {
fetchData();
}, []);

function togglePlantSelection(plant: Plant) {
if (selectedPlants.includes(plant)) {
setSelectedPlants(selectedPlants.filter(item => item !== plant));
} else {
setSelectedPlants([...selectedPlants, plant]);
function handlePlantCardClick(plant: Plant) {
//if in my plants go to [userPlantId] page
if (viewingOption == 'myPlants' && ownedPlants) {
router.push(`my-plants/${ownedPlants.get(plant.id)}`);
}
//if in all plants
else {
//if in select mode add plant to selected
if (inAddMode) {
if (selectedPlants.includes(plant)) {
setSelectedPlants(selectedPlants.filter(item => item !== plant));
} else {
setSelectedPlants([...selectedPlants, plant]);
}
}
//if not in select mode go to [plantId] page
else {
router.push(`all-plants/${plant.id}`);
}
}
}

Expand All @@ -81,11 +98,16 @@ export default function Page() {
<div className="componentsDisplay">
{viewingOption === 'myPlants' &&
(userPlants.length ? (
<InlineDiv>
<div>
{userPlants.map((plant, key) => (
<PlantCard key={key} plant={plant} canSelect={false} />
<InlineDiv
key={key}
onClick={() => handlePlantCardClick(plant)}
>
<PlantCard key={key} plant={plant} canSelect={false} />
</InlineDiv>
))}
</InlineDiv>
</div>
) : (
<div>
<button onClick={() => setViewingOption('all')}>
Expand All @@ -104,7 +126,7 @@ export default function Page() {
{plants.map((plant, key) => (
<InlineDiv
key={key}
onClick={() => togglePlantSelection(plant)}
onClick={() => handlePlantCardClick(plant)}
>
<PlantCard
key={key}
Expand All @@ -123,7 +145,10 @@ export default function Page() {
) : (
<div>
{plants.map((plant, key) => (
<InlineDiv key={key}>
<InlineDiv
key={key}
onClick={() => handlePlantCardClick(plant)}
>
<PlantCard key={key} plant={plant} canSelect={false} />
</InlineDiv>
))}
Expand Down

0 comments on commit 09eee6d

Please sign in to comment.