NuxtN
Nuxt17mo ago
2 replies
Domme

Why do I get a hydration error, and how to fix this?

I have a plugin
setup-state.ts

import type {EnvVars} from "~/datatypes/envvars";
import {useEnvConfigObjectState} from "~/composables/state";

export default defineNuxtPlugin(async nuxtApp => {
    const config = useEnvConfigObjectState();
    let url ="https://URL/api/public/envs";
    const data = await useAsyncData('envs' + url, () => $fetch(url));
    config.setData(data.data.value as EnvVars);
});

And I set a state with the return value from my backend
export function useEnvConfigObjectState() {
    return useObjectState<EnvVars>('env-config');
}

export function useObjectState<T>(key: string, initFn?: () => T) {
    const data = useState<T>(key, initFn);
    const firstFetched = useState<boolean>(`${key}-first-fetch`, () => false);

    const setData = (d: T) => {
        firstFetched.value = true;
        data.value = d;
    };

    return { data, setData, firstFetched};
}

No matter what I try, I always get a hydration error
Was this page helpful?