Vue - Impact on child reactivity when passing props from parent based on stateful dependencies

Currently, I have a situation in my code where I am able to successfully delete an 'exercise' object from the state. However, the deletion does not reflect on the component itself. The parent component receives data from the state and passes the 'exercises' array to the child component for deletion.

Index passes the exercises as selectedRoutine to RoutinePanel

<v-row v-else justify="center">
  <v-col cols="12" sm="9" md="7" class="text-center">
    <RoutinePanel
      :selected-day="selectedDay"
      :selected-routine="selectedRoutine"
    />
  </v-col>
</v-row>

Then RoutinePanel passe each exercise as a prop to HorizontalExercises

<div v-for="exercise in selectedRoutine" :key="exercise.name">
  <HorizontalExercises :exercise="exercise" :selected-day="selectedDay" />
</div>

HorizontalExercises

export default {
  props: {
    exercise: {
      type: Object,
      default: () => {
        return {
          name: 'Exercise',
          sets: 0,
          reps: 0,
          weight: 0,
          id: 0,
        }
      },
    },
    selectedDay: {
      type: String,
      default: () => {
        return ''
      },
    },
  },

Within HorizontalExercises, I have a function that effectively removes the exercise from the state. However, I am facing difficulty in ensuring that it also disappears from the component prop and stops rendering. The exercise only disappears when I re-render the RoutinePanel component.

Here is a simplified version of how the state looks:

  routines: [
    {
      day: 'monday',
      exercises: [
        {
          name: 'bicycle',
          duration: '5 min',
          id: 0,
        },
    ]

Below is the mutation being used:

deleteExercise(state, payload) {
  const routineIndex = state.routines.findIndex(
    (routine) => routine.day === payload.day
  )
  const exerciseIndex = state.routines[routineIndex].exercises.findIndex(
    (exercise) => exercise.id === payload.id
  )
  state.routines[routineIndex].exercises.splice(exerciseIndex, 1)
},

I believe making everything reliant on the state and avoiding passing props might resolve this issue.

Apologies if this seems confusing, this is my first time asking a question.

Answer №1

Have you considered passing values from the state using

:selected-routine="selectedRoutine"
? If your variable is being passed from
this.$store.state.selectedRoutines
and it isn't reactive, you may want to try using getters instead. Check out https://vuex.vuejs.org/guide/getters.html for more information on how to implement getters effectively.

In my project, I found success by mapping getters in my data and passing them down as props. This approach was reactive for me. Additionally, you can map your getters in your computed properties. Learn more about this process at https://vuex.vuejs.org/guide/getters.html#the-mapgetters-helper

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

Contrasting {} and {} as any in TypeScript

Seeking clarity on TypeScript, what sets apart (foo and foo2) from (foo3 and foo4)? (foo and foo2) as well as (foo3 and foo4) produce identical results, yet during compilation, a red underline appears under foo2 and foo3. https://i.stack.imgur.com/lWaHc. ...

How come I am unable to fetch JSON data using JavaScript from PHP?

My goal is to upload a file and extract some processed data from it using PHP. However, I have encountered some issues. Below are my simplified code snippets. HTML CODE <form action="ajax.php" method="post" enctype="multipart/form-data"> <input ...

What is the best way to decode and extract data from this JSON file using JavaScript or AngularJS?

I am encountering an issue while attempting to parse the following JSON. When trying to extract the value using the code below, it returns undefined. Is there a method to successfully parse JSON where the keys contain spaces? { "Transport Fee":{ ...

Retrieve the access ID from the conn.query result

When I run a SQL query, I need to extract the primary key (id) of the event returned so I can use it in another SQL query. However, attempting to access it using result.insertId returns null for the event object. Even logging result.insertId only outputs ...

JavaScript query: Counting items that begin with a specific letter

I may have a partial solution to the problem. By the end, I just want the conclusion to be, "There are two names that begin with the letter B." I am currently not achieving this with my code below. let count = 0; let names = ["Bill", "Julia", "Coral", " ...

Most effective method for converting a table of data to TypeScript

Searching for an effective method to map a table of enum (or interface) data to the correct location. https://i.sstatic.net/5hF2q.png For instance, Smoke Sensor - Push Button can only be linked to SS - PI SYMBOL and Smoke Sensor - PushButton can only be ...

Using ThreeJS/WebGL to Send Functions to Shaders

I have created a custom noise function that accepts a 3D coordinate (x, y, z) and returns a noise value between 0 and 1. I am interested in incorporating this function into my vertex shader to animate vertex positions. Can I access this external function f ...

What is the best location for the frontend server code within an application built using create-react-app?

After using create-react-app to create my app, I am looking to log messages in the server console. Any advice on how to achieve this? I attempted adding index.js to the root folder and creating a server folder, but so far it hasn't been successful. ...

Create a fresh instance of an object in node.js by utilizing the require/new method

I am encountering a beginner problem with node.js where I cannot seem to create objects using the 'new' operator in the index.js file. My goal is to define a simple Person object within a Person.js file, located in the same directory as my index ...

Function not being triggered by button

We are struggling to get a button to trigger a function upon being clicked. Is there a reason why the function is not being called? <body> <button onclick="instagramclick()">Login to instagram</button> <button onclick="myFunction( ...

JavaScript for Audio: How to Play Sound

I've been struggling to make this play a sound in Firefox, IE, or Chrome. No matter what I do, it just won't work. <html> <head> <script type="text/javascript"> function playSound() { var audio = document.createElem ...

Unable to change the value of selected items in checkbox event within a React context

Today marks the beginning of my journey into developing a React application. I am currently faced with the challenge of retrieving the row ID of a checked checkbox in a React table. Utilizing hooks, I have managed to transfer the states to another compone ...

Displaying line breaks <br> on the browser when there are characters stored in the database

Within my mongo database, there is a document containing a field called reviewText: 'this is line 1\nthis is line 2',. This text was entered by a user in a textarea, hence the presence of \n to represent line breaks. I want to display t ...

What is the best way to transfer a JavaScript variable to a JSON format?

Hey there! I'm diving into the world of coding and eager to learn. Recently, I successfully passed a query parameter into a JavaScript variable using the following code: const queryString = window.location.search; console.log(queryString); const urlPa ...

Eliminate quotation marks from an array in order to function as a function with a variable

I receive an array from a JSON object. I then need to loop through the array because it contains function names that I want to execute. The following code snippet works when entered manually: var view_functions = [ header, footer ]; for (i = 0; ...

What is the most effective method for sorting through an array to generate a new array?

Is there a way to filter items from an array based on a specific string and store them in a new array for further manipulation? If so, what would be the most efficient approach to achieve this? Here is the current progress of my code: for (var i = 0; i & ...

How can I make tooltipster display tooltips properly?

I have been struggling to customize tooltips using a library called tooltipster. Here is what I currently have: Head of index.html: <head> <!--TOOLTIP CSS--> <link rel="stylesheet" type="type/css" href="node_modules/tooltipster-master ...

What is the best way to locate a table of a specific class using jQuery selectors?

Is there a way to specifically target a table with the class "d" using jQuery selectors? I'm having trouble making it work... var dTableTags = $(".d table"); For instance, an example table would look like this... <table id="thetable" class="d"&g ...

How to extract and display data when clicking on a Bootstrap switch

I have integrated BootStrap Switch like this: <?php while ($arr = mysql_fetch_array($res)) { ?> <td class="center"> <?php if ($arr['status'] == 1) { ?> <input class="switch" type="checkbo ...

The content of a Puppeteer page mysteriously disappears when transferred to another function

My current project involves using Puppeteer for web scraping on my website. I encountered a strange issue where the await page.content() works fine when I console log the content, but turns out to be null when passed as an argument to another JavaScript ...