Handle Global State management in Nuxt3

Nishant Aanjaney Jalan
3 min readMay 8, 2022

--

Developers usually follow the principle not to expose state in areas where it is not needed. In order to keep this principle intact, we localize the state to individual files. While most of the times, that is perfectly alright to do so, in some cases, we should consider making some global states.

Global states are those data that are exposed throughout the application. Now consider creating a website with User Authentication and Dark Mode. Every page in this website would need to know which user is currently logged in and in which theme should the site be rendered in. Localizing this data could eventually cause bugs as the project grows which will also be difficult to debug.

Problems using Localized state

Passing of data from parent to children

Here, as you see that it is not efficient to have the same data passed down from the top-level components to lower-level components. We need to maintain a single source of truth for easier debugging and improved code readability.

Solution with Global State

Setting a single source of truth in Global State

When the first application is first launched, it will load the data into the global state which is then imported by all the components that require that data.

Nuxt3 Composables

Nuxt3 uses Composables to make this task simpler. Composables are used to leverage Vue3’s composition API to reuse stateful logic. We can start by creating a composables/ directory in the root package of the application and in it, we can create two TypeScript files: useUserData.ts and useDarkTheme.ts.

To start with with creating a composable function, we need to define a function that returns an object with the state and a function that mutates it.

import IUser from '@/types'
const useUserData = () => {
const userData = useState<IUser>('user', () => {})

const setUserData = (user: IUser) => {
userData.value = user
}
return {
userData,
setUserData
}
}
export default useUserData

We have defined a TS Interface with the properties the object will have and pass them to the useState to get the type. In our <script setup />, we can use this method to modify the state of our app.

<script setup lang="ts">
import IUser from '@/types'
const { userData, setUserData } = useUserData()
const { data: user, error } = useAsyncData('user', async () => {
const response = (await $fetch('/api/user')) as IUser
setUserData(response)
})
</script>
[...]

Similarly, we can useUserData in any file that we want and it will gain access to the data.

Conclusion

In cases that we require to have data to be accessed everywhere, we can create global states with the help of Nuxt3 Composables and reuse this single source of truth for the website to behave accordingly.

--

--

Nishant Aanjaney Jalan

Undergraduate Student | CS and Math Teacher | Android & Full-Stack Developer | Oracle Certified Java Programmer | https://cybercoder-naj.github.io