catmal
catmal

Reputation: 1758

Vuex assign null conditionally in action

I have this action in my store:

updateTicketCustomer ({commit, state}, selectedCustomer) {
    axios.patch('/tickets/' + state.currentTicket.id, {
      customer_id: selectedCustomer.id
    })
    .then((response) => {
            commit('UPDATE_TICKET_CUSTOMER', selectedCustomer)
    });  
}

If I wanted to assign null to customer_id, what is the right way to do it? Given that in template I assign null to selectedCustomer, how do I build the conditional to assign null or selectedCustomer.id?

Something like

if (selectedCustomer !== null) {
    customer_id: selectedCustomer.id 
} else {
    customer_id: null
}

Upvotes: 0

Views: 201

Answers (1)

reisdev
reisdev

Reputation: 3393

You could use the conditional operator:

updateTicketCustomer ({commit, state}, selectedCustomer) {
    axios.patch('/tickets/' + state.currentTicket.id, {
      customer_id: selectedCustomer !== null ? selectedCustomer.id : null
    })
    .then((response) => {
            commit('UPDATE_TICKET_CUSTOMER', selectedCustomer)
    });  
}

The syntax is, basically:

<condition> ? <returned if true> : <returned if false>

Upvotes: 1

Related Questions