Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get previous state value in reactjs

When I click New Number button, I get a random number from 0 to 15... This works fine, but now I want when I click Previous Number button, it give me the previous number/state.

For example..

As soon the render runs I get 12. then I click New Number button that give me 4, now I want when I click Previous Number this change the state and give me the number which was in the state before, and it was 4. How to achieve this functionality...

I know componendDidUpdate have prevProp and prevState parameters but can't figure out how to call this on click. Here is my code

class App extends React.Component {
   state = {
      randomNum: ''
   }

   componentDidMount() {
      this.getNewRandomNum()
   }

   getNewRandomNum = () => {
      let randomNum = Math.floor(Math.random() * 15)
      this.setState({ randomNum })
      console.log(this.state.randomNum)
   }

   prevNum = () => {

   }
   render() {
      return (
         <div>
            <h1>{this.state.randomNum}</h1>
            <button onClick={this.getNewRandomNum}>New Number</button>
            <button onClick={this.prevNum}>Previous Number</button>
         </div>
      )
   }
}

Would appreciate your help, hope I am clear.

like image 335
Basit Avatar asked May 13 '19 21:05

Basit


People also ask

How do I get the previous state in react JS?

yes there is a way, by using useRef hook I can save the previous state, we know that the useRef hook works with elements through the dom, but we can also use it in this.

How do you get a value from state in React?

The state and props in React are always in an object format. This means that the value could be accessed from the state and props via key-value pair. To access the normal state object, you can use the key name from the object.

How do you get previous props in React class component?

While there's currently no React Hook that does this out of the box, you can manually retrieve either the previous state or props from within a functional component by leveraging the useRef , useState , usePrevious , and useEffect Hooks in React.

What is the difference between useEffect () and useLayoutEffect () in React?

The useLayoutEffect function is triggered synchronously before the DOM mutations are painted. However, the useEffect function is called after the DOM mutations are painted. I chose this example to make sure the browser actually has some changes to paint when the button is clicked, hence the animation.


2 Answers

Create an additional state-value like previousNum and have that updated with the prevState when you call getRandomNum.

class App extends React.Component {
  state = {
    randomNum: "",
    previousNum: ""
  };

  componentDidMount() {
    this.getNewRandomNum();
  }

  getNewRandomNum = () => {
    let randomNum = Math.floor(Math.random() * 15);
    this.setState(
      prevState => {
        return {
          randomNum: randomNum,
          previousNum: prevState.randomNum
        };
      },
      () => console.log(this.state)
    );
  };

  getPreviousNum = () => {
    this.setState({
      randomNum: this.state.previousNum,
      previousNum: ""
    }, () => console.log(this.state));
  };

  render() {
    return (
      <div>
        <h1>{this.state.randomNum}</h1>
        <button onClick={this.getNewRandomNum}>New Number</button>
        <button
          onClick={this.getPreviousNum}
          disabled={typeof(this.state.previousNum) === "number" ? false : true}
        >
          Previous Number
        </button>
      </div>
    );
  }
}

Also here's the sandbox: https://codesandbox.io/s/7345kyly21

like image 152
Chris Ngo Avatar answered Oct 14 '22 08:10

Chris Ngo


I would suggest to use new state as follows:-

const [prevStart, setPrevStart] = useState(1);
const [page, setPage] = useState(1);

const handelPage = (getPage) => {
    if (getPage < prevStart) {
        ///
    }
    if (getPage > prevStart) {
        //
    }
    const target = `?page=${getPage}`
    createBrowserHistory().push({
        pathname: target,
    });
    setPrevStart(getPage);
    setPage(getPage);
}

Or you can use useRef hook to save the previous state. c

onst [name, setName] = useState("");
    const prevName = useRef("");

    useEffect(() => {
prevName.current = name;
    },[name]);

return (
<>
{name}
{prevName.current}
</>

)

Something like this will solve the issue.

Thanks

like image 26
Hasan Zahran Avatar answered Oct 14 '22 07:10

Hasan Zahran