What is the process for invoking a composable function within a template in Vue 3?

I have implemented a composable that includes a function for handling errors and a template for displaying the errors:

useErrorHandling.js

import { ref } from 'vue';

export default function useErrorHandling() {
  const errors = ref(null);

  function errorFor(field) {
    return errors.value && errors.value[field]
      ? errors.value[field]
      : null;
  }

  return {
    errors,
    errorFor,
  };
}

ValidationErrors.vue

<template>
  <div>
    <span
      v-for="(error, index) in props.errors"
      :key="key(index)"
    >
      {{ error }}
    </span>
  </div>
</template>

<script setup>
const props = defineProps(['errors']);

const key = (index) => {
  return `validation_error_${index}_${Math.random()}`;
}
</script>

During testing on my login form, I noticed that although the errors value is being updated in Vue Dev Tools, it is not being passed to the ValidationErrors component.

Login.vue

<template>
  <div>
    <form action="#" method="POST">
      <div>
        <label for="email">Email Address</label>
        <div>
          <input
              v-model="formData.email"
              id="email"
              name="email"
              type="email"
        </div>
        <validation-errors :errors="errorFor('email')"></validation-errors>
      </div>
  <!-- ... -->
</template>

<script setup>
import { reactive } from 'vue';
import axios from 'axios';
import useErrorHandling from '../../Shared/Composable/useErrorHandling.js';
import ValidationErrors from '../../Components/Form/ValidationErrors.vue';

let { errors, errorFor } = useErrorHandling();

const formData = reactive({
  email: "",
  password: ""
});

const login = async () => {
  axios
    .post('/api/auth/login', {
      email: formData.email,
      password: formData.password
    })
    .then((response) => {
      // Login user
    })
    .catch(error => {
      errors = error.response.data.errors;
    })
}
</script>

I am wondering how I can call the errorFor function from within my Login.vue form?

Answer №1

problems is a reference(), and it's important to update the value of it instead of the actual reference() itself, as this would replace it with an object that is not reactive.

const login = async () => {    
  axios
    .post("/api/auth/login", {
        email: formData.email,
        password: formData.password
    })
    .then((response) => {
        // Log in the user
    })
    .catch(error => {
        problems.value = error.response.data.problems;
    })
}

Additionally, just a quick tip on syntax, you can simplify the errorFor function like so:

function errorFor(field) {
    return problems.value?.[field] ?? [];
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Code: Ensuring URL spaces are maintained

In my Angular 4 project, I have a service with a delete API that requires two strings as parameters. Here is an example of how it looks: this.http.delete(this.url + 'api/v1/ReportingService/collectionID/'+ '45902' +'/'+' ...

I desire to rearrange the items within several arrays of lists

I currently have an array set up like this 0: (5) ["2", "X", "8", "11", "15"] 1: (5) ["1", "5", "X", "X", "14"] 2: (5) ["X", "4", "7", "10", "13"] 3: (5) ["X", "3", "6", "9", "12"] My goal is to swap the position of the digit 1 with the position of digi ...

Creating a sliding menu using React and Headless UI (with Tailwind CSS)

Currently, I'm in the process of developing a slide-over navigation bar or slide menu that features panels opening on top of each other (I'm still searching for the most accurate way to describe it). The main concept revolves around having a sli ...

Is it acceptable for Single Page Web Apps to have multiple requests at startup?

I've been dedicated to developing a Single Page Web App (SPA) recently. The frontend is built with BackboneJS/Marionette, while the backend is powered by Java Spring :(. However, I've noticed that the application's start time could be sluggi ...

What is the best way to transform a ReadonlyArray<any> into an array of any type?

There are certain native angular functions that return a ReadonlyArray, while some native angular callbacks pass ReadonlyArrays as well. Given that my typescript code may be utilized in various scenarios, I prefer not to mandate that all arrays passed to m ...

Implement Material-UI Higher Order Components in a Class-based Component

I'm in the process of incorporating material UI into my class component rather than converting everything to Hooks. I'm unsure which approach would be simpler, utilizing Hooks or adapting what I currently have. https://material-ui.com/styles/bas ...

"Dealing with jQuery and PHP error: Index not defined

Greetings to all! I am attempting to load an external php file using jQuery, and I am encountering an undefined index error due to my use of the GET method in the external php file. Here is the code snippet: Main File <script> $(function() { $( ...

Retrieve data from a jQuery AJAX request and perform further jQuery actions upon its successful completion

I am trying to figure out how to use jQuery AJAX to duplicate a background image and then return information back to the original page. When the '#dupBtn' is clicked, the following AJAX is sent... //DUPLICATE BACKGROUND $('#dupBtn&apo ...

Switching between active navigation items using BootstrapVue and VueJs

If you're using VueJs and Bootstrap Vue and looking to append the "active" tag to your Nav links, check out the following example: <div> <b-nav tabs align="center"> <b-nav-item :active="isActive('/')"& ...

Can someone recommend a design pattern to implement in React?

I have encountered a challenge while working with over a thousand svg elements. Whenever I try to remove, update, or select a single element, it consumes a significant amount of time. The issue lies in the fact that when I modify or delete a specific svg e ...

Storing a component in browser storage using JavaScript and Angular

I am currently working on developing an Angular application that allows users to "favorite" a business card and store it in local memory. I am facing challenges with actually storing the clicked element in the browser's local memory. Furthermore, I f ...

Having trouble showing Firebase data on a basic Vue application

I've been working on a simple Vue+Firebase application that allows users to send strings to the Firebase database and have the messages displayed using the "v-for" directive. However, I keep encountering an error message stating: Property or method " ...

How can we stop KeyboardAvoidingView in React Native from overlapping content?

I'm working on implementing a KeyboardAvoidingView section for a signup form. I've managed to adjust the keyboard properly on both iOS and Android, but instead of increasing the view's height and scrolling up, the KeyboardAvoidingView is red ...

Erase the destination pin on Google Maps

I am currently working on a project that involves displaying hit markers on google maps along with a route from start to finish. Although I have successfully displayed the route, I encountered an issue where both the origin and destination have identical ...

Error Encountered with WebKitSubtleCrypto while utilizing dispatchMessage within a Safari Extension

I'm currently working on developing a Safari extension that allows users to share screenshots of webpages. However, I've encountered an issue when trying to pass the image back to Swift - it triggers an error that causes Safari to become unstable ...

Synchronous JavaScript function with live update

I'm currently working on a function that performs a lengthy task, and I'm looking to implement a feature that notifies the caller of the progress. My end goal is to update the user interface with the current progress status. Here's an examp ...

Determine in JavaScript whether an array includes a function in its elements

Currently, I am adding anonymous functions to an array in the following manner: myArray.push(function(){ /* some unique code here */}); myArray.push(function(){ /* even more unique code here */}); Afterwards, I execute all the functions by doing while ( ...

Assistance is needed in integrating pinch zoom into the css3d_youtube demo in three.js. The trackball controls are causing issues with the

I am facing the challenge of convincing my boss to implement three.js for a CSS3D interface integrated with video providers like YouTube. One of the key requirements is that it must work seamlessly on mobile devices, so I have chosen to demonstrate it on a ...

The Vue warning message pops up when encountering an unfamiliar custom element

Exploring the world of vuejs for the first time, I found myself faced with an error while trying to integrate it into a laravel framework: [Vue warn]: Unknown custom element: <app> - have you correctly registered the component? For recursive compone ...

What is the best way to remove an item from an array?

I'm currently working on implementing a follow/unfollow feature on my page using React/Redux. However, I am struggling to fully grasp how to achieve this. When the user follows 'something', the reducer does the following: case FOLLOW_CITY: ...