Integrating Vue with an existing session storage array

I've developed an API that transmits a video along with all its comments, and in the frontend, the video is called on mount. I have implemented a create comment button that triggers a createComment route to add a comment to the video and store it in the database. However, the newly added comment does not display because after the initial fetch for all videos is made, the code then utilizes session storage to retain the videos without having to call the API on every mount. Is there a way to include the new comment in the session storage? Each comment is associated with its respective video, so each video is represented as an object with a 'comments' array property.

Any assistance with this issue would be greatly appreciated.

HOME PAGE

<template>
    <div class="home">
        <SelectedVideo v-bind:user="user" v-bind:video="videos[0]"/>
    </div>
</template>

<script>
import axios from 'axios';
import SelectedVideo from '../components/SelectedVideo.component';
axios.defaults.withCredentials = true;

export default {
    name: 'Home',
    components: {
        SelectedVideo
    },
    data() {
        return {
            videos: [],
            user: null
        }
    },
    created() {
        if (sessionStorage.homeVideos) {
            console.log('Retrieving from session storage...');
            this.videos = JSON.parse(sessionStorage.homeVideos);
        } else {
            console.log('Fetching from API and saving response to session storage...');
            axios.get('http://localhost:8000/api/v1/videos')
            .then(res => {
                sessionStorage.setItem('homeVideos', JSON.stringify(res.data.data.videos));
                this.videos = JSON.parse(sessionStorage.homeVideos);
            })
            .catch(err => console.log("ERROR: " + err.response.data.message));
        }
    },
    mounted(){
        if (sessionStorage.user) {
            this.user = JSON.parse(sessionStorage.user);
        }
    }
}
</script>

<style lang="scss" scoped>

</style>

Selected Video component

<template>
    <div class="selected">
        <h2 class="selected__title">{{video.title}}</h2>
        <video class="selected__video" :src=video.video controls :poster=video.thumb></video>

        <div style="width: 70%;">
            <div class="selected__details">
                <h3 class="selected__details__views">300 views</h3>

                <div class="selected__thumbs">
                    <div class="selected__like">&#128077; 47</div>
                    <div class="selected__dislike">&#128078; 3</div>
                </div>
            </div>

            <form class="selected__commentbox">
                <label for="comments" class="selected__commentbox__label">Comments</label>
                <textarea v-model="text" class="selected__commentbox__textarea" rows="4" id="comments" placeholder="Type a sweet comment..."></textarea>

                <button @click="handleSubmit" class="selected__commentBtn">add comment</button>
            </form>


            <div v-bind:key="comment._id" v-for="comment in video.comments" class="selected__comments">
                <Comment v-bind:comment="comment"/>
            </div>
        </div>
    </div>
</template>

<script>
import Comment from './Comment.component.vue';
import axios from 'axios';

export default {
    name: 'SelectedVideo',
    data() {
        return {
            text: null,
            videoId: this.video._id,
            userId: this.user._id
        }
    },
    props: ["video", "user"],
    components: {
        Comment
    },
    methods: {
        handleSubmit(event) {
            event.preventDefault();
            this.createComment(this.text, this.videoId, this.userId);
            this.text = '';
        },
        async createComment(comment, video, user) {
            try{
                const res = await axios({
                    method: 'POST',
                    url: 'http://localhost:8000/api/v1/comments/',
                    data: {
                        comment,
                        video,
                        user
                    }
                });
                if (res.data.status === 'success') {
                    // location.reload(true);
                    console.log(res);
                }
            } catch(err) {
                console.log(err.response.data.message);
            }
        }
    }
}
</script>

Answer №1

In order to achieve the functionality you have described, some adjustments are required in your files along with the sessionStorage logic. Firstly, you will need to implement a method that allows the SelectedVideo.vue component to update the video comments within its parent component, which is the Homepage.

Homepage Component

<SelectedVideo v-bind:user="user" v-bind:video="videos[0]" @updateComment=updateComment/>

methods: {
 updateComment(comments) {
  this.$set(this.videos, 0, {...this.videos[0],...comments}); // Update Vue video list
  sessionStorage.setItem("homeVideos", JSON.stringify(this.videos)); // Update sessionStorage for future access
 }
}

Secondly, once you retrieve the new comments, make sure to invoke the parent's updateComment method to update the videos list.

SelectedVideo.vue Component

async createComment(comment, video, user) {
            try{
                const res = await axios({
                    method: 'POST',
                    url: 'http://localhost:8000/api/v1/comments/',
                    data: {
                        comment,
                        video,
                        user
                    }
                });
                if (res.data.status === 'success') {
                    this.$emit("updateComment", res.data.data); // Call parent's update method
                    console.log(res);
                }
            } catch(err) {
                console.log(err.response.data.message);
            }
        }

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

What is the best approach to slowly transition a value to a different one over a set period of time?

if(!isWalking) { isWalking = true; var animation = setInterval(function () {$player.css({'left': "+="+boxSize/25})}, 10); setTimeout(function(){clearInterval(animation)},250); setTimeout(function(){isWalking = false},250); ...

Access Form Mysql Interface with Hypertext Preprocessor and Hyper Text Markup

I currently have an HTML login form and a PHP script that establishes a database connection, allowing users to log in through a basic HTML interface. My objective is to integrate the PHP script into a specific design layout I have created. However, I am en ...

Preserving Selected Option in a Dropdown After AJAX Call in a Partial View

Within my ASP.NET Core web application, I am faced with a scenario where a partial view needs to be integrated into multiple views. This partial view must be able to adapt to dynamic data based on the specific view that triggers its rendering. The area hig ...

PHP code for sending a file alongside displaying text on the browser using the echo command using X-SendFile

I am currently utilizing the X-SendFile Apache Module to facilitate the download of large files from our server. The downloads are functioning as expected; however, I am faced with an issue regarding outputting text to the browser when a download is initia ...

Tips for utilizing the verticesNeedUpdate feature in threejs for refreshing the vertex positions of a 3D cube

let geometry = new THREE.BoxGeometry(500, 500, 500); scene.add(geometry); let edgesGeometry = new THREE.EdgesGeometry(geometry); scene.add(edgesGeometry); let material = new THREE.LineBasicMaterial({ color: 0xffffff, linewidth: 2 }); scene.add(material); ...

How can you animate a MUI v4 Grid element using CSS transitions?

I was exploring the potential of using breakpoints in the MUI v4 component to control the visibility of items in my Grid System. How can I create a smooth CSS transition for b, transitioning from 0px to a defined breakpoint size of 3 for xl? Using % works ...

Is there a way to prevent my <div> from scrolling when the mouse hovers over it?

I currently have a div that is set to scroll infinitely using JavaScript: <script language="javascript"> i = 0 var speed = 1 function scroll() { i = i + speed var div = document.getElementById("content") div.scrol ...

What is the method for retrieving the input value once it has been obscured with asterisks (*)?

Currently, I am in the process of developing a Vue application that will display * characters instead of revealing the actual input entered by the user (similar to a password field). While I have successfully implemented this functionality, I am encounteri ...

Is it possible to employ ES6 modules within Node.js 8?

Is it possible to utilize ES6 module syntax with Node.js beginning from version 8? While there are other similar inquiries on this platform, the answers provided may be outdated. I am interested in knowing if the situation has evolved with the latest ve ...

Unable to reset iframe style height in IE8 using JavaScript

I am encountering an issue with resetting the height of an iframe using JavaScript. Here is the code snippet I am working with: var urlpxExt = document.getElementById('urlPx'); urlpxExt.style.height = "200px"; While this approach works well in m ...

What is the process of transitioning to keyup?

I am looking to replace the ready event with a keyup event. Here is my code snippet: $(document).ready(function(){ $('#coke').validate({ rules : { coek : { required: true, minlength: 6, maxlength: 6 ...

Generate a flexible JSON array in VB.NET

Looking to generate a flexible array that can be converted into a JSON array for visualization with Morris charts. The usual approach in VB.NET is as follows: Dim xArray(2) xArray(0) = New With {Key .TradingDay = "Day1", .Seller1 = 1500, .Seller2 = 160 ...

Pass data between JavaScript and PHP using the Phaser framework

I am trying to pass a JavaScript variable to PHP and then store it in a database. Despite searching for solutions on Google, I have not been successful. Most suggestions involve using AJAX, but the code doesn't seem to work when I try it. I attempted ...

Finding the actual path in any scenario using JavaScript ($.ajax)

Here is the structure of my project: Sil -> css -> js -> clients -> index.php -> response.php index.php I am facing an issue related to the folder 'clients'. My website URL can have different va ...

Error: The property 'rows' cannot be read because it is undefined

While working through the steps outlined in Getting started with Postgres in your React app, specifically when processing and exporting the getMerchants, createMerchant, and deleteMerchant functions, I encountered an error that says: "TypeError: Cannot rea ...

Library for JavaScript English Dictionary

Looking for recommendations for a reliable JavaScript library focused on English dictionaries. I need to access the definitions of input words, so an external library is needed. ...

Problem with Nuxt.js full static build route on AWS Amplify not functioning

I've been working on deploying my nuxt2 app for the past few days and I'm running into some issues. When I include the following flags in my nuxt.config.js file: ssr: false, target: static The dist folder of the app is generated with files tha ...

Programming the tab pages within Chrome

By using JavaScript, I successfully opened a new tab at www.blogger.com from the Main.html page. <script> window.open("https://www.blogger.com"); </script> I am now on the blogger page. My goal is to automatically scroll to the end of the bl ...

"Unleashing the power of infinite Ajax requests upon a drop change event in Knock

I am working with Knockout MVC on my current project and encountering an issue. Whenever I try to pass the viewModel when the Drop Down changes, the method call gets invoked multiple times and the alert message "ok" keeps popping up continuously. Can som ...

Another network request within the ng-repeat loop

My Angular application needs to call web services from two different URLs. The first URL abc.com/student/3 provides a list of students, while the second URL abc.com/parent/idofStudent3 gives the parent's first name when passed the student ID. I have ...