Skip to content

Instantly share code, notes, and snippets.

@Brian-McBride
Created June 21, 2023 18:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Brian-McBride/cf20e653b995d6a544cf95797c4d8b14 to your computer and use it in GitHub Desktop.
Save Brian-McBride/cf20e653b995d6a544cf95797c4d8b14 to your computer and use it in GitHub Desktop.
React Query with XState
export function useStateHook() {
const machineRef = useActorRef(userStateMachine);
const result = trpcReact.user.getById.useQuery('someUserId', {
onSettled(data, error) {
if (error) {
machineRef.send({
type: 'FETCH_ERROR',
error,
});
} else {
machineRef.send({
type: 'FETCH_SUCCESS',
data,
});
}
},
});
useEffect(() => {
const snapshot = machineRef.getSnapshot()?.context || {};
const keys = Object.keys(result);
keys.forEach((key) => {
if (!key.startsWith('is')) return;
if (snapshot[key as never] !== result[key as never]) {
machineRef.send({
type: `FETCH_${key},
data: result[key as never],
});
}
});
}, [machineRef, result]);
}
@jafin
Copy link

jafin commented Aug 16, 2023

Line 27, add a missing backtick `

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment