import {createSlice, createAsyncThunk} from "@reduxjs/toolkit"; import FirebaseQuery from "../../../firebase/firebaseQuery"; import { StudentPlacementData } from "../../../typeDefinitions" import { orderBy, where } from "firebase/firestore"; type InitialActivePlacementSlice = { status: string values: StudentPlacementData | undefined } const initialState: InitialActivePlacementSlice = { status: "", values: undefined, } export const fetchActivePlacement = createAsyncThunk( "studentPlacements/fetchActivePlacement", async ({userId}: {userId: string}) => { const firebaseQuery = new FirebaseQuery(); try { const docs = await firebaseQuery.getDocsWhere(["placements"], [where("active", "==", true), where("uid", "==", userId), where("completed", "==", false), where("draft", "==", false), orderBy("endDate")]); const d = { ...docs as { [key: string]: StudentPlacementData } }; return d[Object.keys(d)[0]] || undefined; } catch (error) { console.log(error) return undefined } } ) export const activePlacementSlice = createSlice({ name: "activePlacement", initialState, reducers: { setActivePlacement: (state, action) => { state.values = action.payload }, editActivePlacement: (state, action) => { state.values = {...state.values, ...action.payload} } }, extraReducers(builder) { builder .addCase(fetchActivePlacement.fulfilled, (state, action) => { state.values = action.payload state.status = "success" }) .addCase(fetchActivePlacement.pending, (state) => { state.status = "loading" }) .addCase(fetchActivePlacement.rejected, (state) => { state.status = "error" }) }, }) export const {setActivePlacement, editActivePlacement} = activePlacementSlice.actions export default activePlacementSlice.reducer;