Using Non Requirement Variables

I have this: query DriversList( $filter: DriverFilter $sorting: [DriverSort] $paging: OffsetPaging ) { drivers(filter: $filter, sorting: $sorting, paging: $paging) { nodes { id name email licenseNumber phone job { id title industry description } joined } totalCount } } But it seems to not work. How can I have the filter/sort/paging not required?
42 Replies
kapa.ai
kapa.ai6mo ago
Hi @Valugar. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave: ---------------------- In GraphQL, you can make arguments optional by not including the ! after the argument type. The ! means that the argument is required. If you want to make the filter, sorting, and paging arguments optional, you can modify your query like this:
query DriversList(
$filter: DriverFilter
$sorting: [DriverSort]
$paging: OffsetPaging
) {
drivers(filter: $filter, sorting: $sorting, paging: $paging) {
nodes {
id
name
email
licenseNumber
phone
job {
id
title
industry
description
}
joined
}
totalCount
}
}
query DriversList(
$filter: DriverFilter
$sorting: [DriverSort]
$paging: OffsetPaging
) {
drivers(filter: $filter, sorting: $sorting, paging: $paging) {
nodes {
id
name
email
licenseNumber
phone
job {
id
title
industry
description
}
joined
}
totalCount
}
}
This means that you can call the DriversList query without providing a filter, sorting, or paging argument and it should work. However, please note that how these arguments are handled on the server-side is dependent on your GraphQL server implementation. The server needs to be set up to handle these arguments being null. If you're using Refine with a GraphQL data provider, you can refer to the Refine documentation on GraphQL usage (https://refine.dev/docs/packages/documentation/data-providers/graphql) for more details on how to structure your queries and mutations. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai6mo ago
<@240371095444652032> kapa.ai is still learning and improving, please let us know how it did by reacting below
unwilling-turquoise
unwilling-turquoise6mo ago
@kapa.ai But when I try to call exactly this, I get the error: Variable "$sorting" of type "[DriverSort]" used in position expecting type' [DriverSort!]". Now over on my backend I have this:
@strawberry.field async def vehicles(self, info: Info, filter: Optional[VehicleFilter] = None, sorting: Optional[List[VehicleSort]] = None, paging: Optional[OffsetPaging] = None) -> Connection[VehicleType]: result = await _generic_query(info, Vehicle, filter, sorting, paging) return Connection[VehicleType](nodes=result["nodes"], totalCount=result["totalCount"]) so it is Optional.
kapa.ai
kapa.ai6mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- The error message you're seeing suggests that the sorting argument in your GraphQL schema is expecting an array of DriverSort where all elements are non-null ([DriverSort!]). This is different from the Optional[List[VehicleSort]] in your Python code, which allows for the list itself to be None, but doesn't say anything about the elements within the list. If you want to make the elements within the sorting array optional as well, you would need to adjust your GraphQL schema to reflect this. Unfortunately, without access to your GraphQL schema, I can't provide specific guidance on how to do this. However, in general, you would need to change the type of the sorting argument from [DriverSort!] to [DriverSort]. This would allow for both the array itself and the elements within the array to be null. Please refer to the GraphQL documentation on input types (https://graphql.org/graphql-js/mutations-and-input-types/) for more information on how to structure the input types in your schema. Also, please note that how these arguments are handled on the server-side is dependent on your GraphQL server implementation. The server needs to be set up to handle these arguments being null. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai6mo ago
<@240371095444652032> kapa.ai is still learning and improving, please let us know how it did by reacting below
unwilling-turquoise
unwilling-turquoise6mo ago
@kapa.ai so for the drivers I have this: @strawberry.input class DriverFilter: id: Optional[StringFilter] = None name: Optional[StringFilter] = None licensenumber: Optional[StringFilter] = None email: Optional[StringFilter] = None phone: Optional[StringFilter] = None joined: Optional[StringFilter] = None job: Optional['JobFilter'] = None and: Optional[List['DriverFilter']] = strawberry.field(name="and", defaultfactory=list) or: Optional[List['DriverFilter']] = strawberry.field(name="or", default_factory=list) @strawberry.input class DriverSort: field: str direction: str As you can see everything is Optional.
kapa.ai
kapa.ai6mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- From your Python code, it's clear that all fields in DriverFilter and DriverSort are optional. However, the error message you're seeing is coming from your GraphQL schema, not your Python code. In GraphQL, the ! symbol indicates that a field is non-null. If your schema defines the sorting argument as [DriverSort!], it means that the array itself can be null, but it cannot contain any null elements. If you want to allow null elements within the sorting array, you would need to change the type of the sorting argument in your GraphQL schema from [DriverSort!] to [DriverSort]. Unfortunately, without access to your GraphQL schema, I can't provide specific guidance on how to do this. Please refer to the GraphQL documentation on input types (https://graphql.org/graphql-js/mutations-and-input-types/) for more information on how to structure the input types in your schema. Also, please note that how these arguments are handled on the server-side is dependent on your GraphQL server implementation. The server needs to be set up to handle these arguments being null. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai6mo ago
<@240371095444652032> kapa.ai is still learning and improving, please let us know how it did by reacting below
unwilling-turquoise
unwilling-turquoise6mo ago
@kapa.ai Ok good. Next - how can I filter all locations so that it will only return the latest location for each different gateway.id? import gql from "graphql-tag"; export const LOCATIONS_LIST_QUERY = gql query LocationssList( $filter: LocationFilter! $sorting: [LocationSort!] $paging: OffsetPaging! ) { locations(filter: $filter, sorting: $sorting, paging: $paging) { nodes { gateway { id serialNumber } location timestamp } totalCount } } ; const { data, isLoading, isError } = useList({ resource: "locations", meta: { gqlQuery: LOCATIONS_LIST_QUERY }, liveMode: "auto", });
kapa.ai
kapa.ai6mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- To return only the latest location for each different gateway.id, you would need to modify your GraphQL query to include a sorting and filtering mechanism that achieves this. However, this largely depends on the capabilities of your GraphQL server and how it's set up to handle such requests. Unfortunately, the provided knowledge sources do not contain specific information on how to modify your GraphQL query to achieve this. However, in general, you might need to sort your locations by timestamp in descending order and then group them by gateway.id. This would ensure that for each gateway.id, the first location in the list is the latest one. Here's a general idea of how you might structure your query:
query LocationsList(
$filter: LocationFilter!
$sorting: [LocationSort!]
$paging: OffsetPaging!
) {
locations(filter: $filter, sorting: $sorting, paging: $paging) {
nodes {
gateway {
id
serialNumber
}
location
timestamp
}
totalCount
}
}
query LocationsList(
$filter: LocationFilter!
$sorting: [LocationSort!]
$paging: OffsetPaging!
) {
locations(filter: $filter, sorting: $sorting, paging: $paging) {
nodes {
gateway {
id
serialNumber
}
location
timestamp
}
totalCount
}
}
In the $sorting variable, you would specify that you want to sort by timestamp in descending order. Please note that this is a general guidance and might not work out-of-the-box depending on your GraphQL server setup. You should refer to your GraphQL server documentation or consult with your backend team for specific instructions. For more information on how to use GraphQL with Refine, you can refer to the Refine documentation on GraphQL usage (https://refine.dev/docs/packages/documentation/data-providers/graphql). ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai6mo ago
<@240371095444652032> kapa.ai is still learning and improving, please let us know how it did by reacting below
unwilling-turquoise
unwilling-turquoise6mo ago
@kapa.ai But I meant if there is a way to deal with it when making the call: const { data, isLoading, isError } = useList({ resource: "locations", meta: { gqlQuery: LOCATIONS_LIST_QUERY }, filters: [ { field: "gateway", operator: "eq", value: "true", } ], liveMode: "auto", }); What is a good filter I should make?
kapa.ai
kapa.ai6mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- The filter you should use depends on the specific requirements of your application. However, based on your question, it seems like you want to filter locations based on the gateway.id. In the filters array, you would specify a filter object where the field is "gateway.id", the operator is "eq" (or another appropriate operator based on your needs), and the value is the specific gateway.id you want to filter by. Here's an example:
const { data, isLoading, isError } = useList({
resource: "locations",
meta: {
gqlQuery: LOCATIONS_LIST_QUERY
},
filters: [
{
field: "gateway.id",
operator: "eq",
value: "<gateway_id>", // replace <gateway_id> with the actual id
}
],
liveMode: "auto",
});
const { data, isLoading, isError } = useList({
resource: "locations",
meta: {
gqlQuery: LOCATIONS_LIST_QUERY
},
filters: [
{
field: "gateway.id",
operator: "eq",
value: "<gateway_id>", // replace <gateway_id> with the actual id
}
],
liveMode: "auto",
});
Please replace <gateway_id> with the actual gateway.id you want to filter by. However, please note that this will only filter the locations based on the gateway.id. It will not ensure that only the latest location for each gateway.id is returned. As mentioned in the previous response, achieving this would likely require modifications to your GraphQL query and/or server implementation. For more information on how to use filters with Refine, you can refer to the Refine documentation on filtering (https://refine.dev/docs/tutorial/adding-crud-pages/mui/adding-sort-and-filters/). ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai6mo ago
<@240371095444652032> kapa.ai is still learning and improving, please let us know how it did by reacting below
unwilling-turquoise
unwilling-turquoise6mo ago
@kapa.ai But I want to get only the latest location per each
kapa.ai
kapa.ai6mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- To get only the latest location for each gateway.id, you would need to modify your GraphQL query to include a sorting and grouping mechanism that achieves this. However, this largely depends on the capabilities of your GraphQL server and how it's set up to handle such requests. Unfortunately, the provided knowledge sources do not contain specific information on how to modify your GraphQL query to achieve this. However, in general, you might need to sort your locations by timestamp in descending order and then group them by gateway.id. This would ensure that for each gateway.id, the first location in the list is the latest one. Please note that this is a general guidance and might not work out-of-the-box depending on your GraphQL server setup. You should refer to your GraphQL server documentation or consult with your backend team for specific instructions. For more information on how to use GraphQL with Refine, you can refer to the Refine documentation on GraphQL usage (https://refine.dev/docs/packages/documentation/data-providers/graphql). ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai6mo ago
<@240371095444652032> kapa.ai is still learning and improving, please let us know how it did by reacting below
unwilling-turquoise
unwilling-turquoise6mo ago
@kapa.ai So over on the backend I have this: @strawberry.field async def locations(self, info: Info, filter: Optional[LocationFilter] = None, sorting: Optional[List[LocationSort]] = None, paging: Optional[OffsetPaging] = None) -> Connection[LocationUpdateType]: result = await _genericquery(info, LocationUpdate, filter, sorting, paging) return Connection[LocationUpdateType](nodes=result["nodes"], totalCount=result["totalCount"])
with: @strawberry.input class LocationFilter: id: Optional[StringFilter] = None gateway: Optional[StringFilter] = None location: Optional[StringFilter] = None timestamp: Optional[DateTimeFilter] = None and
: Optional[List['LocationFilter']] = strawberry.field(name="and", defaultfactory=list) or: Optional[List['LocationFilter']] = strawberry.field(name="or", default_factory=list) @strawberry.input class LocationSort: field: str direction: str and async def _genericquery(info: Info, model: Type[Model], filter: Optional[Any] = None, sorting: Optional[List[Any]] = None, paging: Optional[OffsetPaging] = None) -> Any: query = model.objects.all() if filter: if hasattr(filter, 'vehicle') and getattr(filter.vehicle, 'is', True) is None: query = apply_no_vehicle_filter(query) else: query = apply_filters(query, filter) if hasattr(filter, 'drivers') and filter.drivers: query = apply_driver_filters(query, filter.drivers) if sorting: query = apply_sorting(query, sorting)
total_count = await sync_to_async(query.count)() if paging: query = apply_pagination(query, paging)
results = await sync_to_async(list)(query) return { "nodes": results, "totalCount": total_count } Maybe I need to create a custom query function?
kapa.ai
kapa.ai6mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- Yes, you're correct. To get the latest location for each gateway.id, you would need to modify your _generic_query function to include a mechanism that groups the locations by gateway.id and only returns the latest location for each group. Unfortunately, the provided knowledge sources do not contain specific information on how to modify your _generic_query function to achieve this. However, in general, you might need to use Django's annotate and Max functions to get the latest timestamp for each gateway.id, and then filter the locations based on these timestamps. Here's a general idea of how you might structure your query:
from django.db.models import Max

# Get the latest timestamp for each gateway.id
latest_locations = LocationUpdate.objects.values('gateway__id').annotate(max_timestamp=Max('timestamp'))

# Filter the locations based on these timestamps
query = LocationUpdate.objects.filter(
timestamp__in=[item['max_timestamp'] for item in latest_locations],
gateway__id__in=[item['gateway__id'] for item in latest_locations]
)
from django.db.models import Max

# Get the latest timestamp for each gateway.id
latest_locations = LocationUpdate.objects.values('gateway__id').annotate(max_timestamp=Max('timestamp'))

# Filter the locations based on these timestamps
query = LocationUpdate.objects.filter(
timestamp__in=[item['max_timestamp'] for item in latest_locations],
gateway__id__in=[item['gateway__id'] for item in latest_locations]
)
Please note that this is a general guidance and might not work out-of-the-box depending on your Django setup. You should refer to your Django documentation or consult with your backend team for specific instructions. For more information on how to use Django's annotate and Max functions, you can refer to the Django documentation on aggregation (https://docs.djangoproject.com/en/4.0/topics/db/aggregation/). ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai6mo ago
<@240371095444652032> kapa.ai is still learning and improving, please let us know how it did by reacting below
unwilling-turquoise
unwilling-turquoise6mo ago
@kapa.ai Why am I getting http://localhost:5173/undefined when I try to use: <Button type="primary" onClick={() => { console.log(marker.gateway.vehicle.id) return go({ to: ${edit("vehicles", ${marker.gateway.vehicle.id})}, }); }} style={{ marginTop: '10px' }} > View Vehicle Details </Button> and I have http://localhost:5173/vehicles/edit/1 as a valid place.
kapa.ai
kapa.ai6mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- The issue you're experiencing might be due to the go function not receiving the correct path. The edit function from useNavigation returns a string that represents the path to the edit page of the resource with the given id. However, you're using template literals to construct the path, which might be causing the issue. Try removing the template literals and pass the parameters directly to the edit function:
<Button
type="primary"
onClick={() => {
console.log(marker.gateway.vehicle.id)
return go({
to: edit("vehicles", marker.gateway.vehicle.id),
});
}}
style={{ marginTop: '10px' }}
>
View Vehicle Details
</Button>
<Button
type="primary"
onClick={() => {
console.log(marker.gateway.vehicle.id)
return go({
to: edit("vehicles", marker.gateway.vehicle.id),
});
}}
style={{ marginTop: '10px' }}
>
View Vehicle Details
</Button>
If marker.gateway.vehicle.id is undefined, it means that the id is not available in the marker.gateway.vehicle object at the time when the button is clicked. You might want to add a check to ensure that marker.gateway.vehicle.id is defined before using it. For more information on how to use the edit function from useNavigation, you can refer to the Refine documentation on useNavigation (https://refine.dev/docs/routing/hooks/use-navigation/). ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai6mo ago
<@240371095444652032> kapa.ai is still learning and improving, please let us know how it did by reacting below
unwilling-turquoise
unwilling-turquoise6mo ago
@kapa.ai but I am getting Type 'void' is not assignable to type 'string | Resource | undefined'.ts(2322) types.d.ts(33, 5): The expected type comes from property 'to' which is declared here on type 'GoConfig | GoConfigWithResource'
kapa.ai
kapa.ai6mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- The error message you're seeing is because the go function expects a string or Resource type for the to property, but it's receiving a void type. This is likely because the edit function is not returning a value. The edit function should return a string representing the path to the edit page of the resource with the given id. If it's not returning a value, it might be because the vehicles resource or the id is not defined. Here's how you should structure your code:
<Button
type="primary"
onClick={() => {
console.log(marker.gateway.vehicle.id);
const path = edit("vehicles", marker.gateway.vehicle.id);
go({ to: path });
}}
style={{ marginTop: '10px' }}
>
View Vehicle Details
</Button>
<Button
type="primary"
onClick={() => {
console.log(marker.gateway.vehicle.id);
const path = edit("vehicles", marker.gateway.vehicle.id);
go({ to: path });
}}
style={{ marginTop: '10px' }}
>
View Vehicle Details
</Button>
In this code, we're storing the result of the edit function in the path variable, and then passing that to the go function. This ensures that go receives a string type for the to property. If marker.gateway.vehicle.id is undefined, it means that the id is not available in the marker.gateway.vehicle object at the time when the button is clicked. You might want to add a check to ensure that marker.gateway.vehicle.id is defined before using it. For more information on how to use the edit function from useNavigation, you can refer to the Refine documentation on useNavigation (https://refine.dev/docs/routing/hooks/use-navigation/). ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai6mo ago
<@240371095444652032> kapa.ai is still learning and improving, please let us know how it did by reacting below
kapa.ai
kapa.ai6mo ago
Sorry @Valugar, I seem to be having a bit of trouble. Don't worry though, I've pinged my support and they will try to fix me up! :technologist: Perhaps try again in 15mins?
unwilling-turquoise
unwilling-turquoise6mo ago
@kapa.ai But again const path = edit("vehicles", marker.gateway.vehicle.id); returns undefined.
kapa.ai
kapa.ai6mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- If edit("vehicles", marker.gateway.vehicle.id) is returning undefined, it suggests that either the vehicles resource is not correctly defined in your application, or marker.gateway.vehicle.id is undefined. Here are a few things you can check: 1. Ensure that vehicles is a valid resource in your application. The first argument to the edit function should be the name of a resource that has been correctly set up in your application. 2. Check the value of marker.gateway.vehicle.id. If it's undefined, the edit function might not be able to construct the correct path. You can do this by adding a console.log(marker.gateway.vehicle.id) before the edit function call. 3. If marker.gateway.vehicle.id is undefined, you need to investigate why this is the case. It could be that the marker.gateway.vehicle object does not have an id property, or the vehicle object itself could be undefined. If you're still having trouble, please provide more context or share more of your code, and I'll do my best to help you troubleshoot the issue. For more information on how to use the edit function from useNavigation, you can refer to the Refine documentation on useNavigation (https://refine.dev/docs/routing/hooks/use-navigation/). ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai6mo ago
<@240371095444652032> kapa.ai is still learning and improving, please let us know how it did by reacting below
unwilling-turquoise
unwilling-turquoise6mo ago
@kapa.ai Could the problem be the location I use this function? <MapContainer style={{ flex: 1, width: "100%", height: "100%", zIndex: 0, }} center={[31.505, -90.09]} zoom={5} scrollWheelZoom={true} maxBounds={[ [-80, -180], [90, 180], ]} > <TileLayer attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors' url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" /> <MarkerClusterGroup chunkedLoading polygonOptions={{ opacity: 0, fillOpacity: 0, }} iconCreateFunction={customClusterIcon} disableClusteringAtZoom={17} // Adjust this zoom level based on your needs maxClusterRadius={40} // Lower value means tighter clustering > {markers.map((marker) => ( <Marker key={marker.gateway.id + marker.timestamp} position={[marker.location[1], marker.location[0]] as LatLngExpression} icon={customMarkerIcon(marker.gateway.serialNumber)} > {/* Adding Popup component inside Marker */} <Popup> <div style={{ width: 'auto' }}> <Typography.Title level={5}>Gateway Serial: {marker.gateway.serialNumber}</Typography.Title> <Descriptions size="small" column={1} bordered> <Descriptions.Item label="Latest Update"> {new Date(marker.timestamp).toLocaleString()} </Descriptions.Item> <Descriptions.Item label="Vehicle"> {marker.gateway.vehicle.make} - {marker.gateway.vehicle.model} </Descriptions.Item> </Descriptions> <Button type="primary" onClick={() => { const path = edit("vehicles", "1"); console.log(path) return go({ to: ${edit("vehicles", "1")}, }); }} style={{ marginTop: '10px' }} > View Vehicle Details </Button> </div> </Popup> </Marker> ))} </MarkerClusterGroup> </MapContainer>
kapa.ai
kapa.ai6mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- The location of your edit function call within the MapContainer component should not be an issue. The edit function from useNavigation can be used anywhere within a component that is a child of a Refine component. However, in your code, you're hardcoding the id to "1" in the edit function call:
const path = edit("vehicles", "1");
const path = edit("vehicles", "1");
This will always generate a path to edit the vehicle with the id of 1. If you want to generate a path to edit the vehicle associated with the current marker, you should use marker.gateway.vehicle.id instead:
const path = edit("vehicles", marker.gateway.vehicle.id);
const path = edit("vehicles", marker.gateway.vehicle.id);
Also, make sure that marker.gateway.vehicle.id is defined and is a string. If it's undefined or not a string, the edit function might not work as expected. If edit("vehicles", marker.gateway.vehicle.id) is still returning undefined, it suggests that either the vehicles resource is not correctly defined in your application, or marker.gateway.vehicle.id is undefined. For more information on how to use the edit function from useNavigation, you can refer to the Refine documentation on useNavigation (https://refine.dev/docs/routing/hooks/use-navigation/). ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai6mo ago
<@240371095444652032> kapa.ai is still learning and improving, please let us know how it did by reacting below
unwilling-turquoise
unwilling-turquoise6mo ago
@kapa.ai I now want to save data. For example I have this: const getCenterFromMarkers = (markers: any[]) => { const { data: geofences, isLoading: isLoadingGeofences, isError, error } = useList< GetFieldsFromList<GeofencesListQuery> >({ resource: "events", meta: { gqlQuery: GEOFENCES_LIST_QUERY, }, }); const numMarkers = markers.length; if (numMarkers === 0) { return undefined; } let sumLat = 0; let sumLng = 0; markers.forEach((marker) => { sumLat += marker.location[1]; sumLng += marker.location[0]; }); return [sumLat / numMarkers, sumLng / numMarkers] as [number, number]; }; And I now want to save new geofences. What function should I use and how
kapa.ai
kapa.ai6mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- To save new geofences, you can use the useCreate hook provided by Refine. This hook returns a function that you can call to create a new record for a specific resource. Here's a basic example of how you might use it:
import { useCreate } from "@pankod/refine";

// Inside your component
const { mutate: createGeofence } = useCreate<GeofenceType>("geofences");

// Call this function when you want to create a new geofence
const saveNewGeofence = (newGeofence: GeofenceType) => {
createGeofence({ values: newGeofence })
.then(() => {
// Handle success
})
.catch(() => {
// Handle error
});
};
import { useCreate } from "@pankod/refine";

// Inside your component
const { mutate: createGeofence } = useCreate<GeofenceType>("geofences");

// Call this function when you want to create a new geofence
const saveNewGeofence = (newGeofence: GeofenceType) => {
createGeofence({ values: newGeofence })
.then(() => {
// Handle success
})
.catch(() => {
// Handle error
});
};
In this code, GeofenceType should be a TypeScript type that represents the structure of a geofence. You should replace it with the actual type of your geofences. The createGeofence function takes an object with a values property, which should be the new geofence that you want to create. You can call this function whenever you want to create a new geofence, passing the new geofence as an argument. Please note that this is a general guidance and might not work out-of-the-box depending on your setup. You should adjust the code to fit your specific needs. For more information on how to use the useCreate hook, you can refer to the Refine documentation on useCreate (https://refine.dev/docs/api-reference/hooks/resource/useCreate/). ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai6mo ago
<@240371095444652032> kapa.ai is still learning and improving, please let us know how it did by reacting below
unwilling-turquoise
unwilling-turquoise6mo ago
@kapa.ai what is the difference between pankod/refine and refinedev/core
kapa.ai
kapa.ai6mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- @pankod/refine and @refinedev/core are the same package but with different names. The package was initially published under the @pankod organization on npm, and it was later moved to the @refinedev organization. The @refinedev/core is the current name of the package, and it's the one you should use when installing Refine. The @pankod/refine package is kept for backward compatibility, but it might not receive updates in the future. You can install the package using the following command:
npm i @refinedev/core @refinedev/antd
npm i @refinedev/core @refinedev/antd
For more information, you can refer to the Refine GitHub repository (https://github.com/refinedev/refine/blob/master/examples/app-crm/README.md) and the Refine documentation (https://refine.dev/docs/ui-integrations/ant-design/introduction). ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai6mo ago
<@240371095444652032> kapa.ai is still learning and improving, please let us know how it did by reacting below
unwilling-turquoise
unwilling-turquoise6mo ago
@kapa.ai Why am I getting graphql.error.graphql_error.GraphQLError: Argument 'input' of required type 'CreateLocationSubscriptionFilterInput!' was provided the variable '$input' which was not provided a runtime value. when I try to use the live provider? Here is the subscription I have on the backend: @strawberry.input class CreateLocationSubscriptionFilterInput: gateway: Optional[str] timestamp: Optional[datetime] latitude: float longitude: float @strawberry.input class UpdateLocationSubscriptionFilterInput: gateway: Optional[str] timestamp: Optional[datetime] latitude: Optional[float] longitude: Optional[float] @strawberry.input class DeleteLocationSubscriptionFilterInput: gateway: Optional[str] timestamp: Optional[datetime]
@strawberry.type class Subscription: @strawberry.subscription async def created_location(self, input: CreateLocationSubscriptionFilterInput) -> AsyncGenerator[LocationType, None]: while True: await asyncio.sleep(0.5)
new_locations = await sync_to_async(Location.objects.filter, thread_sensitive=True)( **{k: v for k, v in vars(input).items() if v is not None} ) for location in new_locations: yield LocationType.from_django(location)
kapa.ai
kapa.ai6mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- The error message you're seeing suggests that the input argument of the created_location subscription is not being provided a value at runtime. This means that when the subscription is being executed, the input argument is undefined. In your Refine application, when you're setting up the live provider, you need to ensure that you're providing a value for the input argument. This value should be an object that matches the structure of the CreateLocationSubscriptionFilterInput type. Here's a basic example of how you might set up the live provider in your Refine application:
import { Refine } from "@refinedev/core";
import { createClient } from "graphql-ws";
import { liveProvider } from "./liveProvider";

const gqlWebSocketClient = createClient({
url: "YOUR_WS_URL",
});

const App: React.FC = () => {
return (
<Refine liveProvider={liveProvider(gqlWebSocketClient)}>
{/* ... */}{" "}
</Refine>
);
};
import { Refine } from "@refinedev/core";
import { createClient } from "graphql-ws";
import { liveProvider } from "./liveProvider";

const gqlWebSocketClient = createClient({
url: "YOUR_WS_URL",
});

const App: React.FC = () => {
return (
<Refine liveProvider={liveProvider(gqlWebSocketClient)}>
{/* ... */}{" "}
</Refine>
);
};
In this code, liveProvider should be a function that sets up the live provider for your application. This function should include a subscribe method that sets up the created_location subscription and provides a value for the input argument. For more information on how to set up a live provider with GraphQL subscriptions, you can refer to the Refine documentation on creating a live provider with GraphQL subscriptions (https://refine.dev/docs/guides-concepts/realtime#usage-1). ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai6mo ago
<@240371095444652032> kapa.ai is still learning and improving, please let us know how it did by reacting below