+ Start a Discussion
Lucas AngeliLucas Angeli 

How to filter and display a value based on user input

Hello, I have a datatable with data from a JSON I have parsed, I need to implement a search bar where the user will input a letter and only the values in the table containing that letter will be displayed, can somebody help me? I'm kinda lost
 
<lightning-input type="search" placeholder={placeholder} value={searchKey} onchange={handleSearch}>
      </lightning-input>

          <lightning-datatable key-field="id" 
                                data={mealNames} 
                                columns={columns} 
                                sorted-by={sortBy}
                                sorted-direction={sortDirection}
                                onsort={handleSort}
                                hide-checkbox-column="true"
                                default-sort-direction={defaultSortDirection}>
          </lightning-datatable>
 
import { api, track, wire, LightningElement } from 'lwc';
import getMealData from '@salesforce/apex/MealsRetriever.getMealData';

const columns =[
    {label: 'Meal ID', fieldName: 'idMeal', editable: false, sortable: true, hideDefaultActions: true},
    {label: 'Meal', fieldName: 'strMeal', editable: false, sortable: true, hideDefaultActions: true},
    {label: 'Category', fieldName: 'strCategory', editable: false, sortable: true, hideDefaultActions: true},
    {label: 'Meal Origin', fieldName: 'strArea', editable: false, sortable: true, hideDefaultActions: true},
    {label: 'How to prepare', fieldName: 'strInstructions', editable: false, sortable: true},
];

export default class DataTableWithSortingInLWC extends LightningElement {
    
    @track columns = columns;
    @track sortBy;
    @track sortDirection;
    @track mealNames;
    @api mealSpinner = false;
    @track searchKey;

    @wire(getMealData)
        mealDataResult(result){
            const {data, error} = result;
            if(data){
                this.mealNames = data;
                this.mealSpinner = true;
                this.error = undefined;
            } else if(error){
                this.mealNames = undefined;
                this.error = error;
            }
        }
    
    handleSearch(){
        getMealData(
            {searchKey: '$searchKey'}
        )
        .then(data =>{
            this.mealNames = data;
            this.error = undefined;
        })
        .catch(error =>{
            this.mealNames = undefined;
            this.error = error;
        })
    }

    handleSort(event){
        this.sortBy = event.detail.fieldName;
        this.sortDirection = event.detail.sortDirection;
        this.sortData(this.sortBy, this.sortDirection);
    }

    sortData(fieldname, direction) {
        let parseData = JSON.parse(JSON.stringify(this.mealNames));
        let keyValue = (a) => {
            return a[fieldname];
        };
        let isReverse = direction === 'asc' ? 1: -1;
        parseData.sort((x, y) => {
            x = keyValue(x) ? keyValue(x) : ''; 
            y = keyValue(y) ? keyValue(y) : '';
            return isReverse * ((x > y) - (y > x));
        });
        this.mealNames = parseData;
    }  
}

 
CharuDuttCharuDutt
Hii Lucas
Try the Below Code
LWC

<lightning-input type="search" placeholder={placeholder} value={searchKey} onchange={handleSearch}>
      </lightning-input>

          <lightning-datatable key-field="id" 
                                data={mealNames} 
                                columns={columns} 
                                sorted-by={sortBy}
                                sorted-direction={sortDirection}
                                onsort={handleSort}
                                hide-checkbox-column="true"
                                default-sort-direction={defaultSortDirection}>
          </lightning-datatable>

JS

import { api, track, wire, LightningElement } from 'lwc';
import getMealData from '@salesforce/apex/MealsRetriever.getMealData';
const columns =[
    {label: 'Meal ID', fieldName: 'idMeal', editable: false, sortable: true, hideDefaultActions: true},
    {label: 'Meal', fieldName: 'strMeal', editable: false, sortable: true, hideDefaultActions: true},
    {label: 'Category', fieldName: 'strCategory', editable: false, sortable: true, hideDefaultActions: true},
    {label: 'Meal Origin', fieldName: 'strArea', editable: false, sortable: true, hideDefaultActions: true},
    {label: 'How to prepare', fieldName: 'strInstructions', editable: false, sortable: true},
];
export default class DataTableWithSortingInLWC extends LightningElement {
    
    @track columns = columns;
    @track sortBy;
    @track sortDirection;
    @track mealNames;
    @api mealSpinner = false;
    @track searchKey;
    wiredActivities; 

   @wire(getMealData , {
    searchKey: '$searchKey'
    })
    wiredclass(value){
       this.wiredActivities = value;
       const { data, error } = value;
       if (data) { 
                this.mealNames = data;
                this.error = undefined;
            
           } else if (error) {  
             this.mealNames = undefined;
             this.error = error;
           }  
    }


    
    handleSearch( event ) {
        this.searchKey = event.target.value;
    }
    handleSort(event){
        this.sortBy = event.detail.fieldName;
        this.sortDirection = event.detail.sortDirection;
        this.sortData(this.sortBy, this.sortDirection);
    }
    sortData(fieldname, direction) {
        let parseData = JSON.parse(JSON.stringify(this.mealNames));
        let keyValue = (a) => {
            return a[fieldname];
        };
        let isReverse = direction === 'asc' ? 1: -1;
        parseData.sort((x, y) => {
            x = keyValue(x) ? keyValue(x) : ''; 
            y = keyValue(y) ? keyValue(y) : '';
            return isReverse * ((x > y) - (y > x));
        });
        this.mealNames = parseData;
    }  
}



Apex EXAMPLE
public with sharing class testTable {
    @AuraEnabled(cacheable=true)
    public static List<Account> getAcc( String searchKey) {
       
        String query = 'SELECT Id,Name,Active__c,AccountNumber,Rating,Industry,Type FROM Account';
        system.debug('query---'+query);
        if ( searchKey != Null) {
            String key = '%' + searchKey + '%';
            query += ' WHERE Name LIKE :key';
        }
        
        return Database.query( query );
    }
  }
Please Mark It As Best Answer If It Helps
Thank You!

 
Lucas AngeliLucas Angeli
Hello CharuDutt, I tried your code, but it's not loading the data in the table, also I forgot to mention, I'm using JSON in the table, not a query, this is my Apex Class:
public with sharing class MealsRetriever {
    private static final String MEAL_URL = 'https://www.themealdb.com/api/json/v1/1/search.php?s=';
    private static final String GET = 'GET';
  
    @AuraEnabled(cacheable=true)
    public static List<MealData.Meal> getMealData(String searchKey){
        String key = '%' + searchKey + '%';
        Http httpCallout = new Http();
        HttpRequest req = new HttpRequest();
        req.setEndpoint(MEAL_URL);
        req.setMethod(GET);
        HttpResponse resp = httpCallout.send(req);

        MealData mealResponse = (MealData) JSON.deserialize(resp.getBody(), MealData.class);
        List<MealData.Meal> mealData = new List<MealData.Meal>();
        
        for(MealData.Meal m: mealResponse.meals){
            mealData.add(m);
        }
        /*
        for(MealData.Meal m: mealResponse.meals){
            System.debug('Meal name:');
            System.debug(m.strMeal);
            System.debug('Type of meal: ');
            System.debug(m.strCategory);
            System.debug('Meal area: ');
            System.debug(m.strArea);
            System.debug('How to prepare this meal:');
            System.debug(m.strInstructions);
        }*/

        return mealData;
    }
     
  }

Can you help me?