react-nativeservicewebsocketkuzzle

Connexion object singleton in react native


I'm trying to create a singleton service class in which I instanciate a connection object, which connect to the backend, in order to reuse the connection object in every component, so I've done that:

const {
Kuzzle,
WebSocket
 } = require('kuzzle-sdk');

class KuzzleService {

static instance = null;
static async createInstance() {
    var object = new KuzzleService();
    object.kuzzle = new Kuzzle(
        new WebSocket('localhost'),{defaultIndex: 'index'}
    );
    await object.kuzzle.connect();
    const credentials = { username: 'user', password: 'pass' };
    const jwt = await object.kuzzle.auth.login('local', credentials);
    return object;
}

static async getInstance () {
    if (!KuzzleService.instance) {
        KuzzleService.instance = await KuzzleService.createInstance();
    }
    return KuzzleService.instance;
}

}
const kuzzleService = KuzzleService.getInstance();
export default kuzzleService;

But when I import the service in a component as follow:

import kuzzleService from "../services/kuzzle-service.js";

And I print that:

 async componentDidMount(){
    console.log(JSON.stringify(kuzzleService.kuzzle));
 }

It gives me "undefined". Should I import the service another way ?


Solution

  • This is probably because when you export kuzzleService, the promise given by .getInstance() isn't resolved yet.

    You should export the .getInstance function and await it in componentDidMount, like that:

    export default KuzzleService; // export the singleton directly
    
    async componentDidMount(){
        const kuzzle = await KuzzleService.getInstance();
        console.log(kuzzle);
    }