Samben Jerald
Samben Jerald

Reputation: 117

React - Page is not updating on the state change

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

Upvotes: 2

Views: 1978

Answers (2)

Bhavesh Daswani
Bhavesh Daswani

Reputation: 725

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

Upvotes: 0

DecPK
DecPK

Reputation: 25398

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

Upvotes: 1

Related Questions