Encountering difficulty accessing the object from the props within the created method

After retrieving an object from an API resource and storing it in a property, I encountered an issue where the children components were unable to access the object inside the created method. This prevented me from assigning the values of the object to my data properties as arrays and strings.

Upon inspecting the props from the child component, I observed that my items object was present within it.

"This is the parent component"

<template>
  <v-container grid-list-xl fill-height>
    <v-layout row wrap>
      <v-flex xs6 offset-xs3>
        <message-box :items="source" v-if="source.length > 0"></message-box>
      </v-flex>
    </v-layout>
  </v-container>
</template>
<script>
import MessageBox from './MessageBox'
export default {
  components:{MessageBox},
  data() {
    return {
      room_id: 1,
      source: {},
    };
  },
  created(){
    var app = this;
    axios.get(`/api/room/${app.room_id}/message`)
    .then(res => app.source = res.data.data);
  }
};
</script>

"This is the child component"

<template>
    <div>
        <beautiful-chat
          :participants="participants"
          :titleImageUrl="titleImageUrl"
          :onMessageWasSent="onMessageWasSent"
          :messageList="messageList.messageList"
          :newMessagesCount="newMessagesCount"
          :isOpen="isChatOpen"
          :close="closeChat"
          :icons="icons"
          :open="openChat"
          :showEmoji="true"
          :showFile="true"
          :showTypingIndicator="showTypingIndicator"
          :colors="colors"
          :alwaysScrollToBottom="alwaysScrollToBottom"
          :messageStyling="messageStyling"
          @onType="handleOnType"
          @edit="editMessage"
        />
    </div>
</template>
<script>
import CloseIcon from "vue-beautiful-chat/src/assets/close-icon.png";
import OpenIcon from "vue-beautiful-chat/src/assets/logo-no-bg.svg";
import FileIcon from "vue-beautiful-chat/src/assets/file.svg";
import CloseIconSvg from "vue-beautiful-chat/src/assets/close.svg";
export default {
  props: ['items'],
  data() {
    return {
      room_id: 1,
      participants:[],
      messageList: [],
      limit: 7,
      busy: false,
      auth_uid: User.id(),
      titleImageUrl:
        "https://a.slack-edge.com/66f9/img/avatars-teams/ava_0001-34.png",
      newMessagesCount: 0,
      isChatOpen: false,
      alwaysScrollToBottom: false,
      messageStyling: true,
      showTypingIndicator: "",
      icons: {
        open: {
          img: OpenIcon,
          name: "default"
        },
        close: {
          img: CloseIcon,
          name: "default"
        },
        file: {
          img: FileIcon,
          name: "default"
        },
        closeSvg: {
          img: CloseIconSvg,
          name: "default"
        }
      },
      colors: {
        header: {
          bg: "#4e8cff",
          text: "#ffffff"
        },
        launcher: {
          bg: "#4e8cff"
        },
        messageList: {
          bg: "#ffffff"
        },
        sentMessage: {
          bg: "#4e8cff",
          text: "#ffffff"
        },
        receivedMessage: {
          bg: "#eaeaea",
          text: "#222222"
        },
        userInput: {
          bg: "#f4f7f9",
          text: "#565867"
        }
      }
    };
  },
  methods: {
    sendMessage(text) {
      if (text.length > 0) {
        this.newMessagesCount = this.isChatOpen ? this.newMessagesCount : this.newMessagesCount + 1;
        this.onMessageWasSent({
          author: "support",
          type: "text",
          data: { text }
        });
        axios
          .post(`/api/room/${this.room_id}/message`, { body: text })
          .then(res => console.log("message sent"));
      }
    },
    onMessageWasSent(message) {
      this.messageList = [...this.messageList, message];
    },
    openChat() {
      this.isChatOpen = true;
      this.newMessagesCount = 0;
    },
    closeChat() {
      this.isChatOpen = false;
    },
    handleScrollToTop() {
      
    },
    handleOnType() {
      console.log("Emit typing event");
    },
    editMessage(message) {
      const m = this.messageList.find(m => m.id === message.id);
      m.isEdited = true;
      m.data.text = message.data.text;
    },
  },
  created(){
    
    Array.prototype.forEach.call(this.$props.items, child => {
        this.participants = child.participants;

        this.messageList = child.body;

    });
  },
  computed:{
      itemarr(){
          return this.$props.items
      }
  }
};
</script>

"The console error is

TypeError: Array.prototype.forEach called on null or undefined
"

"The output of my items object is {__ob__: Observer}"

Answer №1

If you're facing a similar issue, try using the `v-if` directive in Vue.js to tackle it. This allows you to wait for an AJAX response before rendering a child component.

<template>
  <v-container grid-list-xl fill-height>
    <v-layout row wrap>
      <v-flex xs6 offset-xs3>
        <message-box v-if="sourceLength > 0" :items="source"></message-box>
      </v-flex>
    </v-layout>
  </v-container>
</template>
<script>
import MessageBox from './MessageBox'
export default {
  components: { MessageBox },
  data() {
    return {
      room_id: 1,
      source: {},
    };
  },
  created() {
    var app = this;
    axios.get(`/api/room/${app.room_id}/message`)
      .then(res => app.source = res.data.data);
  },
  get sourceLength() {
    return Object.keys(this.source).length;
  }
};
</script>

</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

Having trouble serving static files with express.Router?

With my file system becoming more complex, I decided to switch from using app.use(express.static()) to utilizing express.Router(). Initially, I thought I could just replace app.use(express.static()) with router.use(express.static()), but unfortunately, thi ...

What is the process for obtaining the source code for children in React?

Can React extract the source code from children props? Imagine having a component with the following structure... <SomeComp> <Heading>I want to access this code inside the Heading tag</Heading> </SomeComp> How can I retrieve t ...

Create a JavaScript JSON object using a for loop

I am working on creating an object similar to this var flightPlanCoordinates = [ {lat: 37.772, lng: -122.214}, {lat: 21.291, lng: -157.821}, {lat: -18.142, lng: 178.431}, {lat: -27.467, lng: 153.027} ]; Here is my attempt so far for (i = 0; ...

Tips for creating clickable selections with AutoComplete JQuery in ASP.NET and C#

Currently, I am working on a project that involves implementing AutoComplete functionality in a textbox using JQuery AutoComplete. I have included the following file: jquery-ui.js The goal is to make the matched text appear in bold. For example, if I typ ...

How can I dynamically display Material-UI's <MenuItem/> within a <DropDownMenu/> using ReactJS?

In my ReactJS + Material-UI project, I am working with an array named colors that contains different color strings such as "white", "blue", and "green. My goal is to render each color string as a <MenuItem/> within a <DropDownMenu/> component ( ...

Unable to render a rectangle with React's canvas context.fillRect

Could anyone help me with drawing a rectangle using React? I'm having trouble getting it to work. I'm confused as to why the code below isn't showing a rectangle on the screen. class DrawingView{ constructor(props) { this.canva ...

Unable to install Vue-Cli

Currently running node 11.2.0 Continuously encountering this issue. Andrews-MacBook-Pro:vueTutorial aharris$ npm install -g @vue/cli npm WARN deprecated <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8ee6e1ebe5cebba0bea0ba" ...

Mocking a Promise-returning dependency for a React Component in Jest

There's a React component I'm working on that has a dependency like so: import { fetchUsers } from '../../api/'; This function is a utility that returns a Promise. My challenge lies in trying to mock this dependency using Jest. I&apo ...

In my attempt to submit my Laravel form seamlessly without causing the page to refresh

Hey there, I've been struggling to submit my form without refreshing the page. Every time I try, I get an error message in the console log saying the server is rejecting the request. I can't figure out what's going wrong. Can someone please ...

Steps for incorporating events on Jquery UI button

I have a question about utilizing Jquery UI for the first time. After successfully adding a button using Jquery UI, I am now interested in adding events for when a radio switch is turned on and off. When the radiobox is switched on, I want an alert window ...

Switching between all tabs simultaneously in an MDX page (React + Gatsby + MDX) using @reach/tabs

Creating a Tab component for a Gatsby site has proved to be a bit tricky. Imagine having a page with multiple tabs all labeled the same: Heading 1 First tab block Tab 1 | Tab 2 Content Tab 1 Second tab block Tab 1 | Tab 2 Content Tab 1 for the second bl ...

Enhance User Experience with a Responsive Website Dropdown Menu

Currently, I am focused on enhancing the responsiveness of my website and I realized that having a well-designed menu for mobile view is essential. To address this need, I added a button that only appears when the screen size is 480px or lower, which seems ...

There seems to be an issue with the Link component from react-router-dom when used in conjunction with

I am currently utilizing react-router-dom along with Material-ui My main objective is to create a clickable row in a table that will lead to a specific path. Here is the code snippet: .map(client => ( <TableRow key={client.id} component={Link} to ...

Adding a CSS class to a Vue component with a custom prop

I am looking to create a custom component in Vue that has the following props: text = the text to display in the link. icon = the identifier of the icon to display next to the link. < sidebar-link text="Home" icon="fa-home"> Below is the .Vue ...

What could be causing the issue where only one of my videos plays when hovered over using UseRef?

I'm currently working on a project where I have a row of thumbnails that are supposed to play a video when hovered over and stop when the mouse moves out of the thumbnail. However, I've encountered an issue where only the last thumbnail plays its ...

Sharing data between two Angular 2 component TypeScript files

I'm facing a scenario where I have two components that are not directly related as parent and child, but I need to transfer a value from component A to component B. For example: In src/abc/cde/uij/componentA.ts, there is a variable CustomerId = "sss ...

After converting from php/json, JavaScript produces a singular outcome

After running a PHP query and converting the result to JSON using json_encode, I noticed that when I try to print the results using echo, only one entry from the query is output in JSON format. My objective is to make this information usable in JavaScript ...

Tips for setting up the Top Menu and Left Side Menu in your system

You're looking to incorporate both the Top Menu and Left Side Menu. The top menu should remain fixed at the top of the page. Implementing the Left Side Menu below the Top Menu has been a challenge. It's currently covering the top menu, which is ...

What is the best way to inject a service instance into the implementation of an abstract method?

In my Angular application, I have a service that extends an abstract class and implements an abstract method. @Injectable({ providedIn: 'root', }) export class ClassB extends ClassA { constructor( private service : ExampleService) { s ...

Setting the position of a tooltip relative to an element using CSS/JS

I'm struggling to make something work and would appreciate your help. I have a nested list of items that includes simple hrefs as well as links that should trigger a copy-to-clipboard function and display a success message in a span element afterwards ...