Error: Child component received an undefined prop

Within my parent component, I have three child components. The first child component is a form that, upon submission, passes data to the second and third child components through props via the parent component. However, in one of the child components, the prop always remains undefined. I suspect it may be an issue with timing, as using v-if does not seem to resolve the problem.

The Parent Component:


<template>
    <div>
        <patents-searchform v-on:form-submit="processForm"></patents-searchform>
        <patents-word-cloud
          v-if="searched"
          v-show="searched"
          :patentsQuery="patentsQuery"
          :livePage="livePage"
          v-on:pageChange="handlePageChange"
        />
        <patents-search-results
          v-if="searched"
          v-show="searched"
          ref="resultsRef"
          :livePage="livePage"
          :results="patentsQueryResult"
          v-on:pageChange="handlePageChange"
    </div>
</template>


export default {
    data() {
        return {
            livePage: 1,
            searched: false,
            queryform: 'initVal',
            patentsQueryResult: {},
            searching: false,
            patentsQuery: {}
        };
    },
    components: {
        'patents-searchform': PatentsSearchForm,
        'patents-searchresults': PatentsSearchResults,
        'patents-word-cloud': PatentsWordCloud,
    },
    methods: {
        handlePageChange(value) {
            console.log('Homepage::handlePageChange', value)
            this.queryform.page = value;
            this.livePage = value;
            this.fetchData();
        },
        processForm(formData) {
            this.queryform = formData;
            this.fetchData();
            this.patentsQuery['query'] = this.queryform['query']
            this.patentsQuery['searchMode'] = this.queryform['searchMode']
            this.searched = true;
        },
        fetchData() {
            const path = '/flask/searchPatentsNEW';
            this.searching = true;
            if (this.queryform !== 'initVal') {
                axios.post(path, this.queryform)
                    .then((res) => {
                        this.patentsQueryResult = res.data;
                        this.searching = false;
                    })
                    .catch((error) => {
                        console.log(error);
                    });
            }
        }
    }
};

The correctly functioning child component (PatentSearchResults):

<template>
  <b-container>
    <b-card>
          <a id="sTitleCard">Search Results</a>
          <div id="quickStats" style="margin-left: 5%" v-if="this.results.stats">
            {{results.stats.totalAuthors}} inventors across {{results.stats.docCount}} patents
            ({{results.stats.totalQueryTime}} seconds)
          </div>
    </b-card>
  </b-container>
</template>

<script>

export default {
  name: 'Results',
  props: ['results', 'livePage'],
  computed: {
    thisAuthorPage() {
      if (this.results.authors !== null) {
        return this.results.authors; //this.results works fine
      }
      console.log('no authors')
      return [];
    },
  },
  methods: {
  },  
};
</script>

Concerning the child component where the props are undefined:


<template>
    <div>
    <b-card id="patentWordCloudCard" bg-variant="light">
        <b-container>
            <b-form id="queryForm" @submit="onSubmit" @reset="onReset" novalidate>
                <b-row class="d-flex flex-row-reverse">
                <b-button id="btnSubmit" type="submit" variant="primary">Generate query word cloud</b-button>
                </b-row>
            </b-form>
        </b-container>
    </b-card>
    
    </div>
    
</template>

<script>


export default {
    name: 'Patents Word Cloud',
    props: ['patentsQuery'],
    data() {
        return{
            form: {
                query: this.patentsQuery.query,
                searchMode: this.patentsQuery.searchMode
            },
            show: true,
        }
    },
    mounted() {
        console.log(this.patentsQuery) //undefined
    },
    computed() {
        console.log(this.patentsQuery) //undefined
    },
    methods: {
        onSubmit(evt) {
            evt.preventDefault();
            console.log(this.patentsQuery) //undefined
        }
    }
    
}
</script>


Could the issue lie in the timing, where the word cloud component is mounted before patentsQuery is defined? If so, why did v-if fail to delay the component, given that searched evaluates to false until after patentsQuery has been defined?

Answer №1

After some troubleshooting, I managed to successfully interact with patentsQuery using the code snippet below:

<template>
    <section>
    <b-card id="patentWordCloudCard" bg-variant="light">
        <b-container>
            <b-form id="queryForm" align-h="center" @submit="onSubmit" @reset="onReset" novalidate>
                <b-row align-h="center">
                    <b-button align-h="center" id="btnSubmit" type="submit" variant="primary">Create query word cloud</b-button>
                </b-row>
            </b-form>
            
        </b-container>
    </b-card>
    
    </section>
    
</template>

<script>

import axios from 'axios';


export default {
    name: 'Patents Word Cloud',
    props: ['patentsQuery'],
    methods: {
        onSubmit(evt) {
            evt.preventDefault();
            const url = 'flask/patentWordCloud';
            this.loading = true
            axios.post(url, this.patentsQuery).then((res) => {
                    console.log('Data for Patent Word Cloud')
                    console.log(res.data)
                    this.resultingPatents = res.data;   
                })
                .catch((error) => {
                    console.log(error)
                })
        }
    }
}
</script>

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

Display the Sencha Touch Picker with the previously selected option showing

When using the Sencha Touch Picker component, I noticed that if I select a data and then hide the picker, upon showing it again, only the first record is selected each time. I want the picker to display my last selection when shown again. To achieve this ...

Error encountered: Vue.js encountered an unexpected token, which is 'export'

Having an issue with Google location autocomplete, specifically this error: SyntaxError Unexpected token 'export' Here is the link to the functional code: https://codesandbox.io/s/nifty-bardeen-5eock ...

Creating a circular shape with a radius that can be adjusted

I'm trying to create an expanding bubble-like circle of various colors when clicked on a blank page. The circle should continue increasing in size each time it is clicked, only stopping when the mouse click is released. I am looking to use HTML, CSS, ...

What is the best way to utilize useClient in the code of my Next.js project?

I've been attempting to execute the code attached below, but I keep encountering an error stating that a component being imported requires useState and should only be used in a Client Component. However, none of its parent components are marked with " ...

Issue with Photoswipe pswp class Not Getting Properly Cleared Upon Closing Image

My website has a Photoswipe image gallery from . The issue I'm facing is that the CSS class does not reset or clear after closing the gallery for the second time. For example, when a user opens item 1, the images are loaded into the picture div via A ...

Is there a way to insert json data into a form input field using jQuery?

I am attempting to insert the JSON result into an input as the value. This is the code I am using: $.ajax({ type:"POST", url: '{% url "url_searchTour"%}', data: data1, success: function(jsonAjaxResult){ console.log(J ...

Using the React context without explicitly setting the contextType or defining a default context

Is it possible to access the closest context from a provider without having to explicitly define contextType in a component by using this.context? Alternatively, is there a way to establish a default context so that when I use this.context, I automaticall ...

Using Jquery to encase an element in a div while scrolling down and removing it while scrolling up

After some experimentation, I've managed to wrap an element inside a div using jQuery. My next challenge is to wrap it as you scroll down and unwrap it as you scroll up. Do you think this is achievable? Although I have succeeded in wrapping it while ...

Can a single endpoint be used to provide files to web browsers and data to REST requests simultaneously?

I recently completed a tutorial that lasted 7 hours on creating a blog, following it almost completely. The only step I skipped was setting up separate client/server hosting as suggested in the tutorial. Instead, I have a single Heroku server serving the c ...

Understanding conditional statements in JavaScript can greatly enhance your programming skills

Here's a search component that I've been working on. I'm trying to figure out how to handle the scenario where there are no items in the array. Should I use an if statement or is there another approach I should take? Any help would be greatl ...

An exclusive execution of the JavaScript function is ensured

I have a JavaScript function that I want to execute 12 times in a row. Here's my approach: Below, you'll find a list of 12 images: <img id="img1" src=""> </img> <img id="img2" src=""> </img> <img id="img3" src=""> ...

Add custom scripts to individual components within a Vue.js application

After extensive searching, I still can't seem to find a solution to my current issue. My focus is on a Vue project with vue-cli, where I need to inject various scripts into different pages (leveraging vue-router). Here are more specific details: Thi ...

I'm puzzled, can anyone provide clarification on the concept of xml?

Recently, Sheshank S. provided me with a solution to my question, but I failed to grasp its meaning. Can someone please explain it to me? Despite looking through various tutorials on websites and videos, none of them have been able to clarify what this cod ...

Ensure that you patiently wait for the axios method to finish execution before moving on to the

I am currently learning vue.js and struggling with the concept of promises. I need to initialize a variable with data from an API call, but I want to ensure that the Axios call is generic: { data: { list: [], }, methods: { ShowList: function ...

What is the reason onbeforeunload does not fire requests in Safari browser?

Is there a way to ensure that data is saved to the database when a user interacts with the page and also when they refresh it? I have tried using onbeforeunload event, but Safari does not wait for the server request to finish before reloading the page, c ...

Incorporate a new node module into your Ember CLI application

I am interested in integrating the Node.js module https://www.npmjs.com/package/remarkable-regexp into my Ember-CLI project. Can someone guide me on how to make it accessible within the Ember application? I attempted to do so by including the following c ...

Utilizing HTML5's geolocation API to construct a geofence

Is there a way to utilize the HTML5 geolocation API to determine if a user is located in a specific area? I'm considering setting a central latitude and longitude and creating a radius around it, so the site will function as long as the user is within ...

Merge floating and absolute positioning techniques

Creating a calendar exhibiting all events in one div requires precise positioning based on the values of top and height. Let me demonstrate this concept. In the image below, both 6am events are aligned vertically. This alignment issue can be resolved by u ...

Retrieving multiple selected row values using an ASP Repeater

Within my repeater, I have three values bound: a visible "User Name" column, a visible "Business" column, and a hidden field called "UserId". My goal is to implement the following functionality: when a row is clicked, it should highlight in a different c ...

Using Javascript to open a new page and execute a script

I need to be able to launch a new window window.open(url,'_blank'); After that, I want to execute a JavaScript script like this: window.open(url,'_blank').ready("javascript code here"); However, I'm unsure how to accomplish thi ...