I have a context that is used to create, update, list and delete a set of data.
It is created as follows with the following types to be returned.
type TDataContext = {
loading: boolean,
getDataList: () => TData[],
addNewData : (data: TData) => Promise<boolean> ,
editData: (dataId: string, data: TData) => Promise<boolean>,
deleteData: (dataId: string) => Promise<boolean>,
}
const ADataContext = createContext<TGymClientDataContext>({
// How to initialize these here ?
})
export const ADataProvider: FC<{}> = ({children}) => {
const [loading, setLoading] = useState(true)
const [snapshot, loading, error] = useCollection<TDataStore>(db.collection(FIRESTORE_COLLECTIONS.DATA_COLLECTION), {});
const getDataList = async (): TData[] => {
if(loading == true) {
return []
}
if(typeof snapshot == "undefined"){
return []
}
return snapshot?.docs.map((item) => {
const fetched = item.data();
return ({
id: item.id,
doj: fetched.doj.toDate(),
firstName: fetched.firstName,
lastName: fetched.lastName,
})
})
}
// ... Function definitions
const values = {
loading,
getDataList,
addNewData,
editData,
deleteData,
}
return <ADataContext.Provider value={values}>
{children}
</ADataContext.Provider>
}
export const useDataHook = () => useContext(ADataContext)
- I would like to know what will be the good possible way to pass initial data to createContext ?
I'm creating this with the following usage to be expected
const {loading, getClientList, editClientData, addNewClient, deleteClientData} = useGymClient()
The functions are simply expected to return true or false depending on the operations being successful or not.
Another question is,
- The data has to be always caught via getDataList function. is directly passing the snapshot variable down better approach ? In that case, what will be a better initializer for the create context