birdofpreyru / react-native-static-server

Embedded HTTP server for React Native
https://dr.pogodin.studio/docs/react-native-static-server
Other
154 stars 22 forks source link

Using React's useContext to manage server #62

Closed qwertynik closed 1 year ago

qwertynik commented 1 year ago

Given the ambiguity with which the components unmount on the apps, was considering to use the useContext hook to manage a server. So that, the start/stop/restart/crash handling of a server is done from a central space. However, wanted to know about your experience in doing so before beginning to refactor the existing codebase.

Can you confirm if the usage of useContext would enable better server management? Or, are there any other better approaches to handle this?

qwertynik commented 1 year ago

@birdofpreyru

exotexot commented 1 year ago

I think you can create a context, which holds a useRef reference to the server. Then you can use the reference to interact with the server from any component. This is not a change that should be added to this library.

qwertynik commented 1 year ago

This is not a change that should be added to this library.

Not sure why you thought this to be a recommendation for change in the package.

The intent is to know about the pros and cons of this approach, and better yet to know if there are other approaches.

birdofpreyru commented 1 year ago

You can just keep your server instance in a dedicated TS module, outside any RN component — you don't really need a context to do what you wanna do here.

qwertynik commented 1 year ago

Sure, will keep this suggestion in mind when building a project using TS.

Any suggestions on how to best handle a server in a React Native app built using JS?

birdofpreyru commented 1 year ago

:thinking: egh... the same — keep it in a dedicated JS module?

qwertynik commented 1 year ago

Ok. Didn't get it the first time, but now I can see what you are referring to. Something like this should largely work fine, shouldn't it?

const serverProvider = {
    server: null,

    buildServer: function () {
        console.log("Building server...");
        this.server = new Server({...});
        //setup event listener here to track events and reinstantiate server if needed post crashes.
    },

    getServer: function () {
        if (!serverProvider.server) {
            serverProvider.buildServer();
        }

        return serverProvider.server;
    }
}

export default serverProvider;
birdofpreyru commented 1 year ago

Yeap.