Tips on sending data with a unique identifier to the backend through a route parameter

Can anyone help me figure out how to send a message to a specific backend route parameter while passing the current ID? I'm not sure how to inform the system about this ID.

Here's the Vuex action:

postMessage({commit}, payload, id) {
  axios.post(`http://localhost:5000/channels/${id}/messages` ,payload)
    .then((res) => {
      commit(SET_POSTS, res.data)
    })
}

The above code is able to post the action, but I am struggling with passing the channel ID which is located in a different component. How can I achieve this?

postMessage() {
  const postData = {
    description: this.description,
    timestamp: this.timestamp
  };
  this.$store.dispatch("postMessage", postData)
},

In another component, I have a sidebar menu displaying a list of channels similar to Discord. Here's how it looks like:

 p.d-flex.align-items-center.channel-item(v-for="channel in channelName" :key="channel.id")
      strong.hash.mr-3 #
      | {{channel.channel_name}}

Answer №1

One of the main advantages of utilizing Vuex is its capability to establish state in one component and retrieve it from another component. In the receiving component, set a particular state like state.id. Subsequently, you have the option to either pass that id to the action or extract it directly from state within the action.

Below is an example demonstrating how to pass it:

Method

postMessage() {
  const postData = {
    id: this.$store.state.id,
    description: this.description,
    timestamp: this.timestamp
  };
  this.$store.dispatch("postMessage", postData)
}

Vuex actions always expect only 2 parameters - one for the context object (containing commit, dispatch, etc.) and the payload. Adjust your action as follows:

Action

postMessage({ commit }, payload) {
  axios.post(`http://localhost:5000/channels/${payload.id}/messages`, payload)
    .then((res) => {
      commit(SET_POSTS, res.data)
    })
}

If desired, you can opt to destructure the payload argument and utilize the spread operator to separate the id from the rest:

Action

postMessage({ commit }, { id, ...payload }) {
  axios.post(`http://localhost:5000/channels/${id}/messages`, payload)
    .then((res) => {
      commit(SET_POSTS, res.data)
    })
}

An alternative approach would be to exclude the id from the payload and instead retrieve it directly from the state within the action:

Action

postMessage({ state, commit }, payload) {
  axios.post(`http://localhost:5000/channels/${state.id}/messages`, payload)
    .then((res) => {
      commit(SET_POSTS, res.data)
    })
}

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

Modify the date format inside the content of an HTML element or its descendants (excluding their attributes)

I have been trying to reformat some dates using JavaScript. My initial approach was: var regex = /(\d{4})-(\d{2})-(\d{2})/g; $('.container td').each(function() { $(this).html($(this).html().replace(regex, '$3-$2-$1')); ...

Implementing concurrent operations in React Native using Firebase, combining async/await with Promise.all

import fire from '../config/fire'; const db = fire.firestore(); class InitialDb extends Component { constructor(props) { super(props); this.state = { schools: '', students: '', }; } async compo ...

NodeJS encountered a SyntaxError while trying to export the 'routes' object as

const paths = (app) => { app.route('/contact') .get((req, res, next) => { // middleware console.log(`Request from: ${req.originalUrl}`) console.log(`Request type: ${req.method}`) next(); }, (req, res, next) = ...

Encountering a bug in my JSON or object tree viewer in Vue.js 3 where duplicate keys are present when there are multiple similar values

Encountering an issue with the following code: Attempting to create a tree viewer from an object, it works well until encountering identical values which cause key duplication and replacement. View on CodePen: https://codepen.io/onigetoc/pen/rNPeQag?edito ...

Why is it that I am unable to utilize the post data stored in $var within my PHP document when making an Ajax call?

Hey there! I've got this function that makes an ajax call. But, for some reason, the $value I'm passing isn't defined in my showuser.php file. Can you help me figure out why? function showUser2(value) { var xhr = new XMLHttp ...

Ways to transform date into a different structure using JavaScript

Fetching a date from an API gives me this format: 2017-04-20T07:00:00Z How can I convert it to the following format? 20.04.2017 I am using React to render the date: <div>{props.data.day}</div> I attempted to use toISOString().slice(0, 1 ...

Replacing JS/CSS include sections, the distinction between Debug and Release versions

Can you share how you manage conditional markup in your masterpages for release and debug builds? I am currently using the .Net version of YUI compress to combine multiple css and js files into a single site.css and site.js. One idea I had was to use a u ...

Adjust words to fit any screen size as needed

Looking for a small program that can dynamically change a word within an SVG? The goal is to create an effect where regardless of the word or group of words, they always stretch along the entire height (due to a 90-degree rotation) by adjusting the font si ...

Angular 1 and Javascript offer a different approach than using lodash omit and the delete operator

I am facing an issue with a child component where I need to remove properties from an object. Normally, using Lodash, it should work with the following code snippet: this.current.obj = omit(this.current.obj, ['sellerSupportWeb', 'sellerSup ...

Having trouble retrieving information from the Redux store and displaying it in the user interface component

I'm currently diving into the world of Redux and working on a tracker app, but I've hit a roadblock that's had me stuck for days. Your help would be greatly appreciated. Thank you. store.js import { createStore, applyMiddleware, compose } f ...

Open the CSV document

Why am I receiving an error stating ./vacancy-data.csv cannot be found when attempting to pass the csv file into the csvtojson npm package? The csv file is located in the same directory as the code below: var express = require('express'), route ...

Typescript and Mongoose Schema - Common Design Mistakes

I am encountering two issues while defining a schema using mongoose and typescript. Below is the code snippet I'm having trouble with: import { Document, Schema, Model, model} from "mongoose"; export interface IApplication { id: number; name ...

Local server displaying 'Undefined' instead of the unique identifier

My goal is to create a script that will fetch a unique ID from a database when clicked. Despite searching various forums for a solution, I haven't been successful in finding one. <?php $table = mysqli_query($conn ,'SELECT * FROM co ...

Using v-bind:class in Vue.js does not successfully assign a value in the method

Why is the width of my div not changing when I try to bind it to a data attribute that ranges from 0 to 100? <div class="bar" :style="{ width: percentage + '%' }"></div> <script> export default { name: 'app&ap ...

Using AngularJS to inject a variable into the standard filter

Currently, I am attempting to develop a custom filter that mimics the functionality of the standard Angular filter in HTML, with the distinction that it accepts a variable as input rather than a fixed value. For instance, within my html document, you may ...

Tips for maintaining my Countdown timer even after a page refresh

I'm currently tackling JS and I've hit a roadblock. I have successfully created a countdown timer, but now I want it to continue running even after the page is reloaded. I decided to use sessionStorage to store the countdown value and check if t ...

Enhance the "text" attribute of IXMLDOMElement to enable functionality in Chrome

The web application I am currently working on was developed approximately 10 years ago and is only compatible with Internet Explorer. My goal is to make it functional in Chrome as well. I am facing a challenge regarding the "text" property of IXMLDOMEleme ...

Is there a way to include this function in an array without triggering it right away?

In my coding project, I am working with an array of functions that return jQuery deferred AJAX objects known as phoneAjaxCalls. The main function called newPhone is where multiple calls are being pushed and it requires two arguments. function newPhone(tlc ...

Including a label for an array within an unnamed array in a JSON string

Is there a way to transform the following data: [{"name": "Donald"}, {"name": "George"}] Into this format instead: {MyArray: [{"name": "Donald"}, {"name": "George"}]} I am currently working on a database server that I built using node.js, express, an ...

What could be causing the 405 error in my post request?

While attempting to send a post request to Firebase through my Vue app, I keep encountering an error illustrated in this image. I have a webpack server running and the website is on localhost:8080. However, I also have a live version hosted on hostinger a ...