The function str.split() is dividing the text based on individual letters rather than the specified delimiter

I am facing an issue where the string of tags retrieved from firebase needs to be split by ',' and stored in the data() for rendering. The firebase snapshot data is correctly formatted after splitting when viewed in the console like this:

"tag1" "tag2"

However, when I render them in my vue app, they seem to be split at every letter, generating a div for each letter like this:

<div>"t"</div>
<div>"a"</div>
<div>"g"</div>
<div>"1"</div>

I am unsure if this issue is related to my vue app implementation or the firebase call. Any thoughts or suggestions would be appreciated.

I have included some dummy data to illustrate how the tags array within the data should appear in the end.

For reference, here is a snippet of my app:

<div id="container">
<div class="topbar">

          <h3 id="header">DevDeep</h3>

           <div id="searchDiv">
                <b-form-input id="search" v-model="search" placeholder="search articles"></b-form-input>
                <font-awesome-icon id="searchBtn" @click="searchResults()" icon="search" />
          </div>
  </div>

<!--main part of page-->
<div class="bod">

      <div class="sideContainer">
            <h4 id="category">categories</h4>
          <ul id="listoflinks" v-for="cat in categories" :key="cat.toString()">
            <div @click="searchResultsByCat(cat)">{{cat}}</div>
          </ul>
      </div>


<div id="centerContainer">
      <div>
        <h5> Tag list </h5>

        <div class="flexContainer">
            <div id="selectedTags" v-for="tag in tagList" :key="tag.toString()">
                <span id="tag" @click="removeTag(tag)">{{tag}}</span>   
            </div> 
          <font-awesome-icon id="searchBtn" @click="searchbyTags()" icon="search" />
        </div>

         
      </div>

      <div id="artDiv" v-for="art in articles" :key="art.title">
          
          <div @click="gotoArticle(art)" id="thumbnail">
            <h5 >{{art.title}}</h5>  
            <img :src=art.image height="100px" width="100px" alt="article thumbnail">
          </div>
          
<!--TAGS-->/////////////////////////////////////////
        <div class="flexContainer">
            <div id="tags" v-for="tag in art.tags" :key="tag.toString()">
                <span id="tag" @click="addTagToSearch(tag)">{{tag}}</span>
            </div>
        </div>
<!--TAGS-->//////////////////////////////////////////

      </div>
</div>


      <div class="addContainer">adds</div>
  </div>

  <!--main part of page-->

</div>


</template>

<script>
const fb = require('../../fireconfig.js')

export default {
  name: 'Home',
  data:function() {
    return{
       articles: [
         {
           title: 'modern web app security',
           body: 'some content here about web app security',
           image: 'dd',
           tags: ['cyber security','web apps', 'web development']
        },
         {
           title: 'intro to ArcGIS',
           body: 'an article to show users how to do GIS stuff',
           image: 'dwwd',
           tags: ['arcgis','node js','gps services']
        },
        {
           title: 'Vue.js injecting props',
           body: 'this is how to inject vue props into a component',
           image: 'dwwd',
           tags: ['vue','props','components','web development','web apps']  
        }
      ],
      categories:['web development', 'arcgis','cyber security','partnerships'], 
      search: '',
      tagList: []
    }
  },
  props: {
    post: Object
  },
  created(){
                console.log('db post will go here later')
          let ref = fb.db.collection('articles')
          ref.get()
        .then(snapshot => {
          if (snapshot.empty) {
            console.log('No matching documents.');
            return;
          }  
          snapshot.forEach(doc => {  //this works for each doc
            console.log(doc.id, '=>', doc.data());

            doc.data().tags = doc.data().tags.split(",") // its splitting each letter we need to only split at the comma
            console.log(doc.data().tags)

            this.articles.push(doc.data()) //push object into state array
          })

        })
        .catch(err => {
          console.log('Error getting documents', err);
        });
  },
}
</script>

Answer №1

Every time you call the method <code>doc.data()
, a new object will be generated.

When you use <code>doc.data().tags = doc.data().tags.split(","), you are splitting each letter instead of splitting at the comma.

The line above serves no purpose as you are creating a new object but not storing it in a variable. This means that you cannot use it later. Instead, assign the resulting object to a variable and then utilize it.

const data = doc.data(); // create the data object only once
data.tags = data.tags.split(",");
this.articles.push(data);

Since the splitting of the tags didn't persist in the original code, the variable tag in:

<div id="tags" v-for="tag in art.tags" :key="tag.toString()">

Is assigned a single character because art.tags is a string and not an array.

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

Ways to access the files attribute in an input tag in AngularJS without relying on getElementById

I am currently working on file uploads using AngularJS and I have a question regarding how to retrieve input files similar to regular JS. What I want to achieve: HTML: <input type="file" name="file" id="fileImg" accept="image/*"> JS: var file ...

When trying to upload a file using multer, an error occurred stating "Unexpected field

My current issue involves using multer to upload an image from a form. However, I am encountering an Unexpected field error after uploading the image. In my HTML code, I have specified the file and file-model names as myFile. app.js var express = re ...

I'm having trouble understanding why I can't redirect to my GET router after making a POST request

profile.ejs <body> <div id="box"> <h1>Greetings, <span><%= user.name %></span>!<hr> How are you feeling today?</h1> <!-- <form action="/users/logout" method=" ...

A single button that performs multiple actions with just one click

Summary: Seeking assistance in implementing a button that triggers three different actions upon being clicked thrice. Detailed description: On one page of my website, there is an introduction with text and images. I currently have a button that switches t ...

When utilizing the withStyles HOC, innerRef is not included in the passing of other props when passed through React.forwardRef

I have encountered a problem while passing the ref using React.forwardRef to the down component. This method usually works fine. <SomeComponent component={React.forwardRef((props, ref) => <MyComponent innerRef={ref} {...props} />)} .../> Ho ...

Transforming seconds into years, months, weeks, days, hours, minutes, and seconds

Can anyone help me modify Andris’ solution from this post: Convert seconds to days, hours, minutes and seconds to also include years, months, and weeks? I am currently running this code: getDateStrings() { console.log(req_creation_date); const toda ...

How can I best declare a reactive variable without a value in Vue 3 using TypeScript?

Is there a way to initialize a reactive variable without assigning it a value initially? After trying various methods, I found that using null as the initial value doesn't seem to work: const workspaceReact = reactive(null) // incorrect! Cannot pass n ...

Placing pins on Google Maps

I'm attempting to display two separate markers on two individual maps positioned next to each other on my website. <script type="text/javascript"> var map, map2; function initialize(condition) { // setting up the maps var myOptions = { zoo ...

The error message "TypeError: Cannot read properties of undefined (reading 'prototype')" is encountered in Next.js 13 when trying to access the prototype of an

I tried to integrate the downshift library into my project. However, when I attempted to use a basic example from the GitHub repository here, I encountered an error. Current versions: Next.js: 13.2.4 React: 18.2.0 Upon further investigation, it seems lik ...

Modules are being installed to the application's root directory using NPM

I made a mistake and have tried everything to correct it, but no success. Every time I run 'npm install' on a new node project, it installs all dependencies in the root of the application instead of the expected /node_modules/ directory. For ex ...

Error occurred while executing 'npm start' command in ReactJS due to the module 'babel-code-frame' being unable to be located

Every time I attempt to run 'npm start' in the frontend of my application, the terminal spits out a massive error. My package.json file doesn't show any script errors, and I've deleted the 'node_modules' folder and reinstalle ...

Experience the power of TypeScript in a serverless environment as you transform your code from

I have some JavaScript code that needs to be converted to TypeScript. Currently, I have two files: API_Responses.js const Responses = { _200(data = {}) { return { statusCode: 200, body: JSON.stringify(data), }; } }; module.export ...

How to access a variable in an Angular Factory's callback function from outside the factory

Here's a look at the structure of My Factory: .factory('MyFactory', function(){ return: { someFunction: functon(firstParam, secondParam, resultObject) { $http.get(url).success(resultObject); } ...

The sticky navigation and scroll to top features both function perfectly on their own, but when used simultaneously, they do not work

I'm facing an issue with two scripts on my website - when they are separate, they work perfectly fine but together, they don't seem to function properly. What could I be missing here? Script 1: window.onscroll = function() {myFunction()}; var n ...

Tips for showing menu only when a user scrolls on your WordPress site

I've been working on creating an effect where the menu stays hidden until the user starts scrolling. However, I can't seem to figure out why my code is not producing the desired effect. Here is the jQuery code snippet I am using: <script src= ...

Minimize CPU consumption in your threejs application

I've been working on a project where I'm coding Snake in Threejs (I know there are simpler methods). Everything works smoothly until the snake reaches a certain size, causing CPU usage to spike to 50% or more and freezing the entire browser tab. ...

Check the status of the audio source URL using JavaScript

I am currently live streaming audio to my player using the Soundcloud API. <audio></aidio> <source src="soundcloud-track-url"></source> Within my code, I have added an onerror eventListener for both the <audio> and <sourc ...

Angular JS Integration with PapaParse

Currently enjoying the efficiency of PapaParse's CSV parsing and unparsing features. Interested in integrating this with Angular JS - anyone able to assist with this integration? Excited about incorporating PapaParse into an Angular environment. Work ...

Refresh State component following fetch using Redux

Greetings everyone, I'm currently in the process of learning React and Redux. I've encountered a challenge where I am unable to update the state of a specific container using Redux without resorting to a setTimeOut function due to the asynchronou ...

I am seeking a way to securely store my API secret keys while also being able to utilize them for deployment on GitHub pages

How can I securely access my API secret keys for GitHub page deployment while keeping them hidden? I have created a .yml file for GitHub Actions workflows, but I need to know how to retrieve these secret keys from the .vue file. jobs: # The type of runner ...