简体   繁体   中英

Single websocket connection to use across components and store

I have a mobx store which stores all the data from the server.

// stores.js

class User {
    @observable userInfo = null;
    @observable webSocketConnected = false;
}

class Trend {
    @observable latest_trends = null;
}

I have a component to type and send user input to the server via websockets.

@inject('UserStore') @observer
export default class Editor extends React.Component {
    componentDidMount() {
        socket = new WebSocket(newURL);
    }

    sendText = () => {
        // socket.send(...) and update to the store
    }

    render() {
        return (
            <View style={styles.container}>
                ...
                <TextInput
                    value={this.state.text}
                    ...
                    style={styles.text}/>
            </View>
        )
    }

}

I have another component that can vote a user's comment, which I would like to update to the server via websockets.

@inject('TrendStore') @observer
export default class Editor extends React.Component {
    updateComment = () => {
        // socket.send(...)
    }

    render() {
        return (
            <TouchableOpacity onPress={this.updateComment}>
                <Icon/>
            </TouchableOpacity>
        )
    }
}

How can I create one WebSocket connection, so that I can use it with all my store and components?

You would create a websocket service class that gets passed to the constructor of every store, that needs access to the websocket. In your program's main file you initialize all stores and provide them to the component.

const webSocketService = new WebSocketService();
const userstore = new UserStore(websocketService);
const trendStore = new TrendStore(websocketservice);
const stores = { userStore, trendStore };
...
<Provider {...stores} >
   ...
</Provider>

The WebSocketService can have methods like

  • send(message)

  • registerEventListener(event, listener)

So you are giving every store the same instance of websocketService.

Tip: don't write your sending logic or any other business login in the components. Add a method to the specific store like sendMessage(message) and call this method from your component.

Hope this answers your question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM