How can Vue define the relationship on the client-side when submitting a post belonging to the current user?

Currently, I am developing an application using Node.js, specifically Express server-side and Vue client-side, with SQLite + Sequelize for managing the database.

One of the features of this app is that a user can create a post. While this functionality exists, I needed to establish a relationship so that each post can be linked to its author.

I managed to set up this relationship on the server-side using sequelize, and everything seems to be properly configured with the necessary table columns including foreign keys and references.

Now, my next task involves setting the current UserId for the post before it is submitted. Below is the script element for the Vue component responsible for creating posts:

<script>
import PostService from '@/services/PostService'

export default {
    data () {
        return {
            post: {
                title: null,
                body: null
            }
        }
    },
    methods: {
        async submit () {
            try {
                await PostService.post(this.post)
            } catch (err) {
                console.log(err.response.data.error)
            }
        }
    }
}
</script>

In order to access the 'user' object stored in the Vuex state after login, which includes the user's ID, I attempted to modify the post object as follows:

post: {
    title: null,
    body: null
    UserId: this.$store.state.user.id
}

However, inserting this line caused issues with the component's functionality. Even trying to set it within the submit method also resulted in errors.

After exploring different approaches, such as potentially relying on Sequelize generating a setUser method for the post model, I encountered challenges in implementing this feature successfully.

Despite various attempts, problems persisted, and any efforts to resolve them led to more errors or failures in the component's operation.

This dilemma arises especially when attempting to avoid setting any ID at all, which eventually triggers an error indicating that 'Post.UserID cannot be null,' disrupting the once smooth running application.

If anyone has insights or solutions to offer, especially considering my limited experience with Node development, I would greatly appreciate the assistance.

In other parts of the state, such as checking if a user is logged in properly through isUserLoggedIn, there are no issues, and the application functions without crashing in those scenarios.

Answer №1

After some trial and error, I finally got it to work correctly. It's strange because I thought I had tried this solution before, but this time it worked. Here is what I did within the script element of my component:

<script>
import PostService from '@/services/PostService'

export default {
    data () {
        return {
            post: {
                title: null,
                body: null,
                UserId: null
            }
        }
    },
    methods: {
        async submit () {
            this.post.UserId = this.$store.state.user.id

            try {
                await PostService.post(this.post)
            } catch (err) {
                console.log(err.response.data.error)
            }
        }
    }
}
</script>

Now posts are creating and displaying as expected. If there are any technical issues in my approach that I should be aware of, please feel free to point them out, as I am still learning Node, Express, and Vue.

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

Using Jquery for a Second Timer

I have a jQuery function that looks like the one below. The result is displayed in a span, but when the page is reloaded, this span briefly disappears and then reappears. Is there a way to prevent this from happening? I need it to stay visible at all tim ...

When executing JavaScript code, the file remains unchanged and does not alter the URL

I want my form to check a SQL database upon submission and execute a JavaScript file that captures the data into a constant. However, instead of running the JS script on the page as desired, it redirects to a new URL. Is there a way to ensure that the JS ...

The Material-ui paper component fails to display on the screen

The material-ui paper component is implemented on my homepage and functioning correctly. However, when navigating to another page and returning to the homepage, the paper component disappears, leaving only text rendered. Can you help me identify the issue? ...

combine the value of one key with the value of another key within an array

const array = [{ id: 1, name: 'Bob', education: [{ degree: 'bachelors', Major: 'computers' }, { degree: 'masters', Major: 'computers' }] }, { id: 2, n ...

The data that has been retrieved is not currently displayed within the Vue table

I'm currently exploring js/vue and I'm attempting to retrieve data from an API. There's a field where the value is used to fetch data from the API based on that keyword. When I check the console log, I can see that the data is being received ...

What is the process for updating an item in Sequelize?

Seeking help with updating an object in Sequelize. Here is the code I'm using: const updateEmployee = async (req, res) =>{ let {full_name, email, phone_number, address} = req.body const id = req.params.id; Employee.findOne({ wh ...

Express server and create-react-app build facing issues with Glyphicons and fonts functionality

Encountering an issue in the browser console: Failed to decode downloaded font "localhost:5000/static/media/fontname.@#$.woff" OTS parsing error: invalid version tag Came across some suggested solutions like adding a homepage:"./" to package.json. However ...

Building a remote shell using Node.js with the ability to interpret control sequences

Currently, I am working on developing a remote shell using Node.js. Here's the code that I have implemented so far : Client var net = require('net'); var client = net.connect({port: 1234}, function(){ process.stdin.pipe(client); clien ...

Iterating through children of the target element using the .each() method in jQuery

Currently, I am looping through the elements and extracting the src attribute from the child element. This is the snippet of HTML code that I am working with: <noscript data-alt="super awesome"> <img src="http://farm9.staticflickr.com/8235/85 ...

Generating hills with PlaneGeometry in Three.js

Currently, I am searching for a straightforward technique to generate non-uniform hills in Three.js. By utilizing particles and positioning them with a sine wave algorithm like the following snippet: x = Math.random() * 1000 y = Math.sin( x / freq ) * ...

Showcasing the selected menu item's value on an Angular button

I've encountered an issue where I have a list of menu items: <md-menu-item ng-value="menuItem.value" ng-repeat="menuItem in filtermenu.menuItems" ng-click="activeFilterCtrl.selectedfilter(menuItem)" translate> <md-button> {{ m ...

Unshifting values in a JavaScript array only if they exist in another array

I have two arrays of objects - one containing selected data and the other containing general data that needs to be displayed General data for display const arr = [ { id: "1", name: "Skoda - Auto" }, { id: "2" ...

What is the best way to organize class usage within other classes to prevent circular dependencies?

The engine class presented below utilizes two renderer classes that extend a base renderer class: import {RendererOne} from "./renderer-one"; import {RendererTwo} from "./renderer-two"; export class Engine { coordinates: number; randomProperty: ...

Issue with displaying current date and time dynamically (JavaScript/JQuery)

In order to create a real-time chat using websockets, I want to show the time of a message posted in this format: "% sec/min/hour/day now". After conducting some research, I came across two functions that I have modified : // Get the TimeStamp va ...

Utilizing Express Router Parameters

I am facing an issue with fetching Student models from a mongodb instance based on their username. Below is the mongoose model defined for the Student: var studentSchema = mongoose.Schema({ local : { username : String, password : String, } }); ...

What are the steps to program a bot to respond to different types of media messages (such as pngs, mp4

I have been attempting to elicit a reaction from him based on the media message, but my attempts have been fruitless so far. It seems that the only time it reacts is when there is no text within the message... which complicates things. Can anyone provide s ...

Tips for handling the final row of a CSV file in Node.js with fast-csv before the 'end' event is triggered

After using fast-csv npm, I noticed that in the code provided below, it processes the last row (3rd row) of CSV data only after triggering the "end" event. How can this issue be resolved? ORIGINAL OUTPUT : here processing request here processing re ...

AJAX, JavaScript, and hyphens

Can anyone help me understand why the ajax statement in my code does not accept the '-' symbol? I've had issues with this before and ended up modifying a lot of things on the backend of my site to use '_' instead, which worked. Is ...

Node.js: Deciding between res.render and res.redirect in express-session

On my website, I have a login page and a myservices page. Once a user logs in, they should be redirected to the myservices page where their username is displayed. In the login.js file, the following code is used: req.session.user = "abc"; res.redirect(&a ...

Troubles with submitting jQuery validation plugin via AJAX

Whenever I try to use the jQuery validation plugin for validating a form within a Bootstrap modal, the validation does not work and the form cannot be submitted. This is the code for the Bootstrap modal form: <div class="modal fade" id="form-content" ...