0

It must be pretty regular issue.

I'm passing props down to the children and I'm using it there to request to the endpoint. More detailed: I'm clicking on the list item, I'm checking which item was clicked, I'm passing it to the child component and there basing on prop I passed I'd like to request certain data. All works fine and I'm getting what I need, but only for the first time, ie. when refreshing page incoming props are gone and I cannot construct proper URL where as a query I'd like to use the prop value. Is there a way to preserve the prop so when the page will be refresh it will preserve last prop.

Thank you!

Murakami
  • 3,474
  • 7
  • 35
  • 89
  • Possible duplicate of [How to keep React component state between mount/unmount?](https://stackoverflow.com/questions/31352261/how-to-keep-react-component-state-between-mount-unmount) – Hardik Modha Sep 11 '18 at 13:23
  • As far as I know, when you refresh a web page, it is a like brand new app. To get values after web page refreshing, you should save them to localstorage or sessionstorage. When page refreshed, you can check if there is any data in localstorage or sessionstorage. If there is data, you can get and set your props or redux state. @Barth – oakar Sep 11 '18 at 13:58
  • Also, mount/unmount really different then refreshing page @Hardik Modha – oakar Sep 11 '18 at 14:05

1 Answers1

2

(You might want to take a look at: https://github.com/rt2zz/redux-persist, it is one of my favorites)

Just like a normal web application if the user reloads the page you're going to have your code reloaded. The solution is you need to store the critical data somewhere other than the React state if you want it to survive.

Here's a "template" in pseudo code. I just used a "LocalStorage" class that doesn't exist. You could pick whatever method you wanted.

class Persist extends React.Component {
    constuctor(props) {
        this.state = {
            criticalData = null
        }
    }
    componentDidMount() {
        //pseudo code
        let criticalData = LocalStorage.get('criticalData')
        this.setState({
            criticalData: criticalData 
        })
    }

    _handleCriticalUpdate(update) {
        const merge = {
            ...LocalStorage.get('criticalData')
            ...update
        }

        LocalStorage.put('criticalData', merge)
        this.setState({
            criticalData: merge
        })
    }

    render() {
        <div>
            ...
            <button 
                onClick={e => {
                    let update = ...my business logic
                    this._handleCriticalUpdate(update) //instead of set state
                }}
            >
            ....
        </div>
    }
}

By offloading your critical data to a cookie or the local storage you are injecting persistence into the lifecycle of the component. This means when a user refreshes the page you keep your state.

I hope that helps!

Daniel B. Chapman
  • 4,647
  • 32
  • 42