Inertia.JS , Laravel closing modal if no validation errors

Viewed 1035

So I have the following method:

methods: {
    submit() {    
      this.$inertia.post('/projects', this.form);
      this.openModal = false;
      
    },
},

But it closes my modal even if there are validation errors. I've also tried with

this.$inertia.post('/projects', this.form);
      if(!this.$page.props.errors) {
              this.openModal = false;
}

Which doesn't close the modal if there are validation errors, but it doesn't close it if the there are no validation errors.

1 Answers

this.$inertia.post is executed asynchronously, so this.openModal = false will most likely finish before you get a response from the server. If you want to see what I mean, put sleep(10); somewhere in the controller for the /projects route - before the Inertia gets back the response from the server, whatever code you have after this.$inertia.post will be executed.

I am assuming your controller redirects back. If your modal is closed by default when the page is loaded, then you can keep the modal open when errors are present with the following:

this.$inertia.post(
    this.route("/projects"),
    this.form,
    {
        preserveState: (page) => Object.keys(page.props.errors).length > 0,
    }
);

See Component state section in the Inertia docs for reference.

Related