I'm trying to replicate the apollo function writeQuery using urql
I'm using urql with vue to fetch the current state of my items in the DB but I'm also using MQTT to catch events and those event are updates of my current items and I don't want to request again all the items in every MQTT event to update the UI I only want to update the one needed
Is there a way or another approach you can suggest to me?
Right now I'm using Pinia to store the urql result and in every MQTT event I'm updating the pinia store but the urql store is not updated
I know that I can reexecute the query on every event but I'm not sure if that is the best idea.
import { CombinedError, gql, useQuery } from '@urql/vue';
import { defineStore } from 'pinia';
import { useMqtt } from '../composable/mqtt-repository';
import { IrrigationDevice, IrrigationDevicesResponse } from './types';
import { Ref, onMounted, ref } from 'vue';
const query = gql`
query IrrigationDevices {
irrigationDevices {
id
name
lastMetric {
state
}
}
}
`;
export const useIrrigationStore = defineStore('irrigation', () => {
let irrigationDevices: Ref<IrrigationDevice[]> = ref([]);
let isFetching: Ref<boolean> = ref(false);
let error: Ref<CombinedError | undefined> = ref(undefined);
const { client } = useMqtt('irrigation/#');
client.on('message', (topic: string, message: any) => {
if (topic === 'irrigation/state_changed_stored') {
const { data } = JSON.parse(message);
const device = irrigationDevices.value.find((device: IrrigationDevice) => device.id === data.irrigationDeviceId);
if (device) {
device.state = data.state;
}
}
})
const turnIrrigationState = (deviceName: string, newState: boolean) => {
client.publish(`irrigation/${deviceName}/change_state`, newState ? '1' : '0');
}
const requestIrrigationDevices = async () => {
const result = await useQuery<IrrigationDevicesResponse>({
query,
});
isFetching.value = result.fetching.value;
error.value = result.error.value;
irrigationDevices.value = result.data.value!.irrigationDevices.map(e => ({
id: e.id,
name: e.name,
state: e.lastMetric?.state ?? false,
}))
}
onMounted(() => {
requestIrrigationDevices();
});
return {
irrigationDevices,
isFetching,
error,
turnIrrigationState,
}
})