Home > Back-end >  Populate input data with result from API nuxt 3
Populate input data with result from API nuxt 3

Time:11-16

I have a nuxt 3 app that fetches data from the API. I would like to use that data to populate the input fields in the template but I keep getting an error.

Here is a snippet of my code

<script setup>

const config = useRuntimeConfig();

const route = useRoute();

const router = useRouter();

const { data: pkg } = useFetch(
  () => '/api/id/1/'
);

const request = ref({
  field: pkg.value.field_value,
});

When I console.log(pkg.value.field_value) I get the value printed on the browser developer tools console tab but on hard refresh, I get the error Cannot read properties of null (reading 'field_value')

The reason why I need to dynamically set the value of field is so that I am able to update it.

Anyone encountered that problem before and how did you address it

CodePudding user response:

Add await to the useFetch function because at the first rendering the pkg is not available :

<script setup>

const config = useRuntimeConfig();

const route = useRoute();

const router = useRouter();

const { data: pkg } = await useFetch(
  () => '/api/id/1/'
);

const request = ref({
  field: pkg.value.field_value,
});
  • Related