Home > Software engineering >  React - Page is not updating on the state change
React - Page is not updating on the state change

Time:07-03

I'm first looping the data and displaying the state value. When we click on the entered text this should be reversed and displayed in the page. But, the state is getting updated. But, not updating in the page.

CodeSandbox - https://codesandbox.io/s/nice-framework-5odlcs?file=/src/App.js

CodePudding user response:

React is smart enough to know when to re-render the component. If you are passing same array (same object reference) then It won't re-render. So you have to clone it or create a new array.

You can first create a clone of new array and then reverse the string.

DEMO

  const h3ClickHandler = (index) => {
    setData((prev) => {
      const clone = [...prev];
      clone[index] = clone[index].split("").reverse().join("");
      return clone;
    });
  };

Or You can use map over to return new element and rever if the array index matched the clicked one as:

DEMO

  const h3ClickHandler = (index) => {
    setData((prev) =>
      prev.map((str, i) =>
        i === index ? str.split("").reverse().join("") : str
      )
    );
  };

CodePudding user response:

EDIT: You can also mutate state using immerjs library below how it would look like with immer js DEMO

    const h3ClickHandler = (index) => {
      setData(
      produce((draft) => {
        draft[index] = 
         draft[index].toString().split("").reverse().join("");
      })
    );
  };

======

Orignal Answer: There is an issue with the h3ClickHandler you are mutating the state instead you should return a new instance of the array that is to do in an immutable way You can modify the below h3ClickHandler method to below and give it a try:

const h3ClickHandler = (index) => {
    setData((prev) => {
      const dataVal = data[index].toString().split("").reverse().join("");
      const updateData = prev.map((p, i) => {
        if (i === index) {
          return dataVal;
        }
        return p;
      });

      console.log(updateData);
      return updateData;
    });
  };

I have create the code sandbox example, which you can give it a try https://codesandbox.io/s/vigilant-lamarr-7ou2yg?file=/src/App.js:309-650

  • Related