Why my useState, does not reprint the array with the new elements in it?

Why my useState, does not work property? In a filter search bar, I'm trying to reprint the elements of an Array depending on the input but I can't get the reprinting right,

const clickSearchIcon = (query) => {
    let filteredItems = [];
    console.log('ITEAM ALL:', itemsAll); //works --> 9
    setItems(itemsAll); //DONT work, --> 1st time: 9 , second time: 0; both times must be 9
    console.log('items:', items);
    //filtrar items que concuerdan con el query
    items.map((item) => {
      if (item.title === query) return filteredItems.push(item);
    //repintar item filtrado con el query
    setItems(filteredItems); //does work

this is the complete file, in case you need more context

This is the browser and console.logs

Submitted December 26th 2020 by Admin


itemsAll has never changed so you don't need to update it in clickSearchIcon function. To filter items, you can use filter instead of map.

const clickSearchIcon = (query) => { const filteredItems = items.filter((item) => item.title === query); setItems(filteredItems);

Admin | 9 months ago


allItems has never been changed. setItems does not see it has been changed. because allItems is an array, although you changed its items, but the object itself (think it as a pointer) has not been changed.

Just use a new variable, make a copy of allItems, and use setItems on the new variable.

let newItems = [...allItems]
// modify newItems

Admin | 9 months ago

Relevant Questions