Search code examples
javascriptreactjsstatehtml-framework-7

Framework7 - Global State in React Application


I need a central storage solution for my Data. In my example for the Shopping cart Items or User Credentials. But I want to use the Lifecycle of React. So when the Data changes my Application should render the DOM Tree again.

Framework 7 provides the "data" and "params" Properties, that I can access on every single page through the "this.$f7" Object. But there is not "setData" function to rerender the DOM when Data changes.


Solution

  • I implemented the context of my App:

    import UserContext from '../context/UserContext';
    
    export default class extends React.Component{
    
      constructor(props){
        super(props);
        this.state = {
          shoppingcartitems: [],
        }
      }
    
      render(props) {
        return (
          <UserContext.Provider value={{ 
                state: this.state, 
                setState: function(param){this.setState(param)}.bind(this)
            }}>
          <App params={f7params} onInit={this.onInit()}>
            ...
          </App>
          </UserContext.Provider>
          );
      }
    }
    

    Now I can Access it in every other File I need it:

    import UserContext from '../../context/UserContext';
    
    export default class CartPage extends React.Component {
        static contextType = UserContext;
    
        componentDidMount() {
            console.log(this.context.state);
    
            this.context.setState({ hello: "World!"});
        }
    
    }