简体   繁体   中英

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

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);
};

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
setItems(newItems)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM