Joff
Joff

Reputation: 12187

reactJS copying object to a new state var or passing state in the tree

The title was a bit hard to explain...here is what I am doing....

I have a react app that is hitting an API and returning some results, users have the option to perform CRUD operations on those results when they get them, which happens in a bootstrap modal popup window...

React suggests lifting state up to the parent, which is ok...but then I am left with a situation where the user modifies the state in the UPDATE operation, then changes their mind and backs out and is left with the modified state in the original window (which leaves me no choice but to fetch from the API again to refresh it)

option 1: I could copy the stateful object to a new object and modify that...throwing it away if the user cancels, but in this case I run into javascript quirk about copying objects and references (How do I correctly clone a JavaScript object?) which I am not experienced enough to solve.

option 2: I can pass the object to the UPDATE child class somehow and then set the state there, but this seems to go against reactJS philosophy, and it shows because I ran into errors while trying it.

I basically need a way to temporarily modify the state and leave a way to go back to the original but I have not found any solution (due to react structure and javascript quirks...)

class base extends React.Component {
    constructor() {
        super(props);
        this.state = {foo: "bar"}
    }

    render() {
        // I want to be able to modify the state from BootStrapPopup with
        // the option to go back to the original state if the user backs
        // out from committing updating the object through the API
        return (
            <BootStrapPopup />
        )
    }

Upvotes: 0

Views: 732

Answers (1)

Shubham Khatri
Shubham Khatri

Reputation: 281784

You can keep a state that stores the prevState like

class base extends React.Component {
    constructor() {
        super(props);
        this.state = {foo: "bar", prevFoo: ""}
    }
    ChangeState = () => {
       this.setState((prevState) => { prevFoo: prevState.foo, foo: "newBar"});
    }
    RevertChange = () => {
       this.setState({foo: this.state.prevFoo});
    }
    render() {

        return (
            <BootStrapPopup />
        )
    }

Upvotes: 2

Related Questions