Created
June 21, 2023 18:20
-
-
Save Brian-McBride/cf20e653b995d6a544cf95797c4d8b14 to your computer and use it in GitHub Desktop.
React Query with XState
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Line 27, add a missing backtick `