0

I have a child lwc which receives an array as a public property (@api inputArray), does some work on it, and then returns another array via events to the parent.

When the input array is changed by the parent, I want the code to run and the event to be sent. Currently, I have a for:each within the lwc.html that runs through the array (but displays nothing), then when the inputArray is changed, the lwc is re-rendered and I can use the renderedCallback to send my event.

But it seems kind of awkward to have a for:each loop doing nothing in order to trigger the re-render and run this code.

What is the good and convenient way of recognising and handling change in a lwc public property? Or is what I'm doing already the best?

(For the sake of simplicity below, I've left out the code that is altering the array and just returning a string)

childLWC.js

import { LightningElement, api } from 'lwc';

export default class FilterLWC extends LightningElement {
    
    @api inputArray;

    renderedCallback(){
        console.log('rendered');
        this.dispatchEvent(new CustomEvent('childEvent', {detail: {newList: "woooo" }}));
    }
}

childLWC.html

<template>
    <div>
        <template for:each={inputArray} for:item="arrayElement">
            <p key={arrayElement}>
            </p>
        </template>
    </div>
</template>

1 Answer 1

2

The appropriate way to deal with this is to make the API property a getter/setter pair...

@api get inputArray() {
    return this._inputArray;
}

set inputArray(value) {
    this._inputArray = value;

    this.reactToUpdate();
}

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.