Search code examples
reactjsredux

How to connect or subscribe to Redux Store without using connect()?


In react application, I have a constant file where I create a object of HTML strings, in these HTML strings I have to pass some dynamic values from the states stored in store, below is the structure of my constant file(its a sample structure, actual file has approx 18-20 html string objects):

import store from '../store';
let storeState = store.getState();
let dynamic_Data_from_Store = storeState.initAppReducer.clientData;

const HTML_MESSAGES = {
    REQUEST_OPTIONS: "<div>"+dynamic_Data_from_Store+"</div",
    ENQUIRY_OPTIONS: "<div>"+dynamic_Data_from_Store+"</div",
    OTHER_VALUES: "<div>"+dynamic_Data_from_Store+"</div"
}

export default HTML_MESSAGES;

In the above code snippet only initial store state will be available but not the updated store state in future. As per documentation, we have to have the component subscribed to redux store to get the updated states through connect()

But as you can see that this file is not the component and is created to have the constants defined, then, how can I subscribe this to get the updated state?


Solution

  • This is what I have come up with after reading between the lines of comment by @remix23

    In my component, wherever I am going to consume my HTML_MESSAGES, I will connect it to store and then replace the defined placeholders with my required store state. For Example:

    My Component which consumes my constant file:

    import React, { Component, Fragment } from 'react';
    import { connect } from 'react-redux';
    import CONSTANTS from '../../../utils/Constants';
    import HTML_MESSAGES from "../../../config/html_inserts";
    
    class InsertMessages extends Component {
    
        createDataMessage = (type) => {
            let msg = '';
            switch (type) {
                case CONSTANTS.REQUEST_OPTIONS:
                    msg = HTML_MESSAGES.REQUEST_OPTIONS;
                    break;
                case CONSTANTS.ENQUIRY_OPTIONS:
                    msg = HTML_MESSAGES.ENQUIRY_OPTIONS.replace('<clientData>', this.props.cliendData);
                    break;
                default:
                    break;
            }
            return msg;
        }
    
        insertMessages = (type) => {
     let content = this.createDataMessage(type);
    
    let insert = //gql insert query
    return insert;
        }
    
        render() {
            return (
                <Fragment>
                    {this.insertMessages(type)}
                </Fragment>
            )
        }
    }
    
    const mapStateToProps = state => {
        return {
            cliendData: state.initAppReducer.clientData
        };
      };
    
    export default connect(mapStateToProps, null)(InsertMessages);