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

CamKem's avatar
Level 10

Conditional logic not working on Vue Pinia store action

Hello, I am trying to implement condition logic to control the flash message response & action given when a new member is being added. This is the exported useTeamStore that has the createMember action that is being called which is in the TeamStore.js.

export let useTeamStore = defineStore("team", {
    state: () => ({
            name: '',
            max: 1,
            avatar: '',
            members: [{
                id: 1,
                name: 'John',
                email: '[email protected]',
                status: 'pending',
            }],
        }),
    actions: {
        // async will only fill the store once the view is mounted & the action is called
        async fill() {
            let data = await import('@/team.json');
            this.$state = data.default;
        },

        addSpots(number) {
            this.max += number;
            flashMessage('The team size is increased', 'success');
        },

        // implement the ability to change the status of a team member
        changeStatus(id, status) {
            let member = this.members.find((m) => m.id === id);
            member.status = status;
            flashMessage('The team member status is updated', 'success');
        },

        // below is the implementation of the CRUD operations

        createMember(name, email) {
            if (this.members.length === this.max) {
                flashMessage('The team is full', 'error');
            } else if (this.members.find((m) => m.email === email)) {
                flashMessage('The email is already in use', 'error');
            } else if (!name) {
                flashMessage('The name and email are required', 'error');
            } else if (!email) {
                flashMessage('The name and email are required', 'error');
            } else {
                // work out what the next id is
                let ids = this.members.map((m) => m.id);
                let max = Math.max(...ids);
                // create the member
                let member = {};
                member.id = max + 1;
                member.name = name;
                member.email = email;
                member.status = 'pending';
                member.avatar = `https://i.pravatar.cc/50?u=${member.email}`;
                this.members.push(member);
                // show a flash message
                flashMessage('The team member is added', 'success');
            }
        },
        readMember(id) {
            return this.members.find((m) => m.id === id);
        }
        ,
        updateMember(id, data) {
            // find the member in the array
            let member = this.members.find((m) => m.id === id);
            // update the member
            member.name = data.name;
            member.email = data.email;
            member.avatar = data.avatar;

            flashMessage('The team member is updated', 'success');
        }
        ,
        deleteMember(id) {
            // remove the member from the array
            let index = this.members.findIndex((m) => m.id === id);
            this.members.splice(index, 1);

            flashMessage('The team member is deleted', 'error');
        },
    },
    getters: {
        spotsRemaining() {
            return this.max - this.members.length;
        },
    }
});

This is the form that submits the data to the action

  <Modal :show="showModal" @close="showModal = false">
    <template #default>
      <h2 class="text-2xl font-bold mb-2">Add a new member</h2>
      <form class="flex flex-col gap-y-4" @submit.prevent="team.createMember(name, email, status); showModal = false">
        <div class="flex flex-col gap-y-1">
          <label for="name" class="text-lg font-medium">Name</label>
          <input type="text" id="name" v-model="name" class="border border-gray-300 px-4 py-2 rounded" />
        </div>
        <div class="flex flex-col gap-y-1">
          <label for="email" class="text-lg font-medium">Email</label>
          <input type="email" id="email" v-model="email" class="border border-gray-300 px-4 py-2 rounded" />
        </div>
        <button type="submit" class="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded">Add Member</button>
      </form>
    </template>
  </Modal>

When I don't enter any data it still add a new team member to the stored team.members array. When I use an email that already exists it still adds the new member. I want the condition logic to prevent a new member being added & not the member being added when ever the form is submitted as it working now. Can you please help me work out how to do this correctly. Thanks for you help!

0 likes
1 reply
LaryAI's avatar
LaryAI
AI
Best Answer
Level 58

To prevent a new member from being added when the form is submitted without any data or with an email that already exists, you need to update the createMember action in the TeamStore.js file to return a boolean value indicating whether the member was successfully created or not. Then, in the form submission handler, you can check this value and show the appropriate flash message.

Here's how you can update the createMember action:

createMember(name, email) {
  if (this.members.length === this.max) {
    flashMessage('The team is full', 'error');
    return false;
  } else if (this.members.find((m) => m.email === email)) {
    flashMessage('The email is already in use', 'error');
    return false;
  } else if (!name || !email) {
    flashMessage('The name and email are required', 'error');
    return false;
  } else {
    // work out what the next id is
    let ids = this.members.map((m) => m.id);
    let max = Math.max(...ids);
    // create the member
    let member = {};
    member.id = max + 1;
    member.name = name;
    member.email = email;
    member.status = 'pending';
    member.avatar = `https://i.pravatar.cc/50?u=${member.email}`;
    this.members.push(member);
    // show a flash message
    flashMessage('The team member is added', 'success');
    return true;
  }
},

And here's how you can update the form submission handler:

<form class="flex flex-col gap-y-4" @submit.prevent="handleSubmit">
  <!-- form fields -->
  <button type="submit" class="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded">Add Member</button>
</form>
methods: {
  async handleSubmit() {
    const created = this.team.createMember(this.name, this.email);
    if (created) {
      this.showModal = false;
      flashMessage('The team member is added', 'success');
    }
  },
},

In the form submission handler, we call the createMember action and store the returned value in a variable called created. If created is true, we close the modal and show a success flash message. If created is false, we don't close the modal and show an error flash message based on the condition that was not met in the createMember action.

Please or to participate in this conversation.