简体   繁体   中英

Array doesn't update after adding new item, using React Hooks

I have an array that shows a set of items attached to a user. The array checks it first if the current user is on the item's inventory and then displayed as 'user name' and 'date borrowed' on a table. The adding feature is done in a modal, and suppose to update the table.

The problem is everytime I add, delete or update, the table doesn't update at all. Also this table is an expandend component of another table (react-data-table-component)

Here is the useState, and useEffect of my table:

const InventoryTable= ({ 
selectedUser, 
items, 
getItems, 
getUsers 
}) => { 
   useEffect(() => { 
   getItems(); 
   getUsers(); 
  }, []); 

  const [data, setData] = useState([]);

  useEffect(() => {
    let data= [];
    data= items?.filter((item) =>
      item?.users.some(
        (user) => parseInt(user?.id) === parseInt(selectedUser?._id)
      )
    );

    setData(data);
  }, []);

Note: selectedUser, is the user from the main table that was selected and this current table is to show the itms attached to it.

If I add data on the setData(data); }, []); setData(data); }, []); it crashes. Adding data, selectedUser, and items on the dependency arrays loads it non-stop that causes to crash the page

useEffect method takes 2 parameters as input.

  1. callback
  2. dependency

If the dependency is empty array it will be called in the similar way as Class Component with componentDidMount and componentWillUnmount lifecycle methods.

if dependency is present then the callback will be called after the UI in painted.

So clearly you have missed required dependency

I'm not sure that i understand the whole concepts of your code because it is just a small part of the code. But useEffect() will run accordingly if you want it to run as ComponenentDidMount you will use the code that you said above however in your case you want to update delete add it means you want to detect the change in data so you need to include data within the brackets like this

`useEffect(() => {

 let data= [];
data= items?.filter((item) =>
  item?.users.some(
    (user) => parseInt(user?.id) === parseInt(selectedUser?._id)
  )
);
setData(data);

}, [data,items,selectedUser]);`

似乎您忘记传递itemsselectedUser来影响依赖项数组。

Maybe I am wrong, but have you tried renaming data property inside useEffect? It should have problem, that you are setting state without set callback. Try also set useState default value to [] instead of {} (object).

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