Actual working button - changing status on click (also fetching on click)
Mon Feb 26 2024 09:45:59 GMT+0000 (Coordinated Universal Time)
Saved by @rafal_rydz
import { useState } from "react"; import { useSupabaseClient } from "@supabase/auth-helpers-react"; import { Button } from "ui"; import { Database } from "../../types"; export const UserShiftStateButton = () => { const [isOnline, setIsOnline] = useState(false); const [isLoading, setIsLoading] = useState(true); const [error, setError] = useState(""); const supabaseClient = useSupabaseClient<Database>(); const toggleShiftStatus = async () => { setIsLoading(true); try { const { data: { session }, } = await supabaseClient.auth.getSession(); if (session) { const { data: userData, error: userError } = await supabaseClient .from("UserLastWorkedOn") .select("shift_start") .eq("user", session.user.id) .maybeSingle(); console.log("data", userData); if (userData === undefined || userData === null) { throw new Error("User not found"); } if (userData.shift_start !== null) { // User is on shift so toggle to off shift const { error: updateError } = await supabaseClient .from("UserLastWorkedOn") .update({ shift_start: null, }) .eq("user", session.user.id); if (updateError) throw updateError; setIsOnline(false); const { error: insertError } = await supabaseClient .from("UserHistory") .insert([ { action: "END SHIFT", user: session.user.id, }, ]); if (insertError) throw insertError; } else { // User is off shift so toggle to on shift const { error: updateError } = await supabaseClient .from("UserLastWorkedOn") .update({ shift_start: new Date().toISOString(), }) .eq("user", session.user.id); if (updateError) throw updateError; setIsOnline(true); const { error: insertError } = await supabaseClient .from("UserHistory") .insert([ { action: "START SHIFT", user: session.user.id, }, ]); if (insertError) throw insertError; } } } catch (err) { setError("Failed to toggle shift status"); console.error(err); } finally { setIsLoading(false); } }; return ( <> <Button action={toggleShiftStatus} // disabled={isLoading} text={isOnline ? "Go Offline" : "Go Online"} /> {error && <p>Error: {error}</p>} </> ); };
Comments