Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

guilheb's avatar

(Vue/Inertia) Best pratice when loading form data from an API?

I currently use lepikhinb/momentum-modal to easily load modals with Laravel/Inertia. The things that bugs me the most is that there is a delay between clicking a button and the modal actually showing up. That concern is also shared with the Inertia creator.

So I'm trying to find a better way. I use PrimeVue's Dynamic Dialog component to load my UserForm component in a modal, which is used both for user creation and edition.

I have a loading icon that spins until an axios call to the back-end is completed in onMounted to get the user's information.

I'm using Inertia's useForm() (which I love) and the main annoyance is that it seems I need to declare all form fields first, and then populate them one by one after the axios call.

const api_response = ref({});

const form = useForm({
    field1: null,
    field2: null,
    field3: null,
    field4: null,
    field5: null,
    field6: null,
    field7: null,
    field8: null,
    field9: null,
});

onMounted(() => {
    axios.get('some url').then(function (response) {
        api_response.value = response.data;

        form.field1 = response.data.user.field1;
        form.field2 = response.data.user.field2;
        form.field3 = response.data.user.field3;
        form.field4 = response.data.user.field4;
        form.field5 = response.data.user.field5;
        form.field6 = response.data.user.field6;
        form.field7 = response.data.user.field7;
        form.field8 = response.data.user.field8;
        form.field9 = response.data.user.field9;
    });
});

Am I doing things the "right" way? What is the best practice in that regard?

0 likes
1 reply
LaryAI's avatar
Level 58

The current approach of declaring all form fields first and then populating them one by one after the axios call is not the best practice. A better approach would be to use the setFormFields method provided by Inertia's useForm hook to set all the form fields at once. Here's an example:

const api_response = ref({});

const form = useForm({
    field1: null,
    field2: null,
    field3: null,
    field4: null,
    field5: null,
    field6: null,
    field7: null,
    field8: null,
    field9: null,
});

onMounted(() => {
    axios.get('some url').then(function (response) {
        api_response.value = response.data;

        form.setFormFields(response.data.user);
    });
});

This way, all the form fields will be set at once, and the loading icon will spin until the axios call is completed.

Please or to participate in this conversation.