automatically generate unique keys for keyed composables #13963
Description
We have an opportunity to improve DX by adding transform plugins for vite & webpack to automatically generate a fallback key at compile time that can be used if users have not added keys themselves. These keys will be specific to the file the call to the keyed composable is located in.
useFetch
This is particularly relevant, given issues like #13951 and #13583. With useFetch
, we generate key based on options, but sometimes these options may be functions, and then we get mismatches between client/server because the code is transpiled slightly differently and .toString()
doesn't yield the same result.
Usage
<script setup>
// these will now work as expected, though they will not share state with identical call
// to useFetch in another component
const { data } = await useFetch(() => 'https://my.api.com')
const { data } = await useFetch('/api/test', { transform: data => data.test })
</script>
useAsyncData
This allows a convenience factor, where a user can avoid generating keys for one-off calls to useAsyncData
(or export a composable that auto-generates a shared key used between all calls to it.
Usage
<script setup>
// this is automatically keyed to this individual component,
// wherever it is used in the app
const { data } = await useAsyncData(async () => ({ foo: 'bar' }))
</script>
useState
This is more DX. It saves users having to create keys for state. (Alternative would be to add an alias for useState
called useLocalState
that has this behaviour, and require users create keys for useState
if we feel it's in any way confusing to allow omitting the key.)
Usage
Composable
// this will expose a unique state - every time it's imported from this file it will access the same state
export const useMyState = () => useState()
Component
<script setup>
// this state will be unique to this component, everywhere it is used in the app
const a = useState()
</script>
Activity