How to declare model class in react native and pass whole model class in second screen by use of react navigation

Viewed 15184

Is proper way to declare model class like java and how to pass this into second screen in react native?

export default class UserModel {

    stateName;
    username;
    email;
    mobile;
    gender;
    address;

    constructor() {}

    setStateName(stateName) {
        this.stateName = stateName;
    }
    setUserName(username) {
        this.username = username;
    }

    setEmail(email) {
        this.email = email;
    }

    setMobile(mobile) {
        this.mobile = mobile;
    }

    setGender(gender) {
        this.gender = gender;
    }

    setAddress(address) {
        this.address = address;
    }
}
2 Answers

Step 1: Make UserModel.js

class UserModel {

    constructor() {
        stateName,
        username,
        email,
        mobile,
        gender,
        address;
    }

}

Note: Do not Export it if you don't want to set globally.

Step 2 : Screen1.js - Set UserModel and pass from screen1.

_handlePress = async () => {

        UserModel.username = "Vishal Patoliya"

        this.props.navigation.navigate('UserList',{userData: UserModel});

    }

Step 3 : Receiving model class at another screen.

render() {
        console.log(TAG, "render() Called.")

        const UserModel = this.props.navigation.getParam('userData');

        console.log("Username", UserModel.username)
}

OutPut :

01-16 17:30:32.085  4541  5638 I ReactNativeJS: 'Username', 'Vishal Patoliya'

Edit:

After some discussion, this was required answer:

this.props.navigation.navigate('UserList', { userModel: userModel });

this.props.getParam('userModel', /* optional default value */);

I assume this is your UserModel.js. Now you are able to import the model like other components:

import UserModel from './location/UserModel';

But if you do it like this, you'd have to instanciate UserModel every time you import it.

If you'd like to prevent this, just instanciate a UserModel and export it inside the UserModel.js and import the instance anywhere.

Like this:

class UserModel {
    //...
}

export default new UserModel();

other way might be:

export class UserModel {
    //...
}

const GlobalUserModel = new UserModel(); 
export default GlobalUserModel;

to choose in other files what to import:

import { UserModel } from './location/UserModel'; //get new instance

or

import GlobalUserModel from './location/UserModel'; //get global instance

If imported via { UserModel }, you have to instanciate first: new UserModel()

...or vice versa.

Related