简体   繁体   中英

React Hooks: array not updating/changing in useEffect Hook

Here is my code:

const [state, setState] = useState({
    isLoaded: false,
    data: [], // data here
    isError: false,
  });
  let { isLoaded, data, isError } = state;

...

const [refundItem, setRefundItem] = useState(0);
  useEffect(() => {
    const refundedData = data.map((item) => {
      // refundedData not changing here
      return item.paymentId === refundItem ? { ...item, isRefund: true } : item;
    });
    setState({ ...state, data: refundedData });
  }, [refundItem]);

data is an array of objects. I want to find an element of data whose property paymentId is refundItem , and change that element's isRefund property value into true (-> originally, all elements' isRefund properties are false ).

The problem is that refundedData is always the same as data .

Sorry I am new to React and Javascript, and thanks for helping me.

edit: OMG I forgot to mention that paymentId and refundItem are both number type. Sorry for mistake😭😭

It seems that useEffect might not be triggered at all due to refundItem not being changed. Try using debugger to see if useEffect function is triggered or add console log to useEffect and check if it prints anything.

 useEffect(() => {
    console.log(`USE_EFFECT - dataLength: ${data.length} / refundedId: ${refundedItem}`);
    const refundedData = data.map((item) => {
      // refundedData not changing here
      return item.paymentId === refundItem ? { ...item, isRefund: true } : item;
    });
    setState({ ...state, data: refundedData });
  }, [refundItem]);

EDIT1: Looking at Zohaib answer it also got me thinking you have state refundItem . From the name I would think it might be a whole object and you need to get id from it return item.paymentId === refundItem.id ? ... return item.paymentId === refundItem.id ? ... or just as he said it's you might be comparing two different types and === also compares types. Examples:

1 === 1(number === number) => true
"1" === 1(string === number) => false
"1" === "1"(string === string) => true
"1" == 1(string == number) => true

Also check how are you using refundItem . Since it's a state element you need to use setRefundItem method and not simple assign since that will prevent React from knowing that there are any changes eg.

const updateRefundedItem = (newItem) => {
  refundedItem = newItem.id // <= this is bad
  setRefundedItem(newItem.id) // <= this is good :P
}

Possible issue => refundItem is of type number, while item.paymentId is in string.

If this is the case then the SOLUTION is to replace

===

with

==

and the issue will be resolved

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