RN App - receiving [TypeError: undefined is not an object (evaluating '_ref.trackName')]

Currently building React Native (0.66) mobile using Mac, npm (6.14.13), Xcode w/mobile device simulator (iPhone 12, iOS 14.3) and trying to integrate with Realm (10.10). I have a user input screen (AddTrack.js), in which I’m using the useState hook to capture input values. Have been trying to use starter code from the RN tutorial and have not successfully pushed a new document to local Realm DB yet. Receiving the following error, which I don’t fully understand: [TypeError: undefined is not an object (evaluating ‘_ref.trackName’)] when attempting to ‘create track’. What’s undefined here? ‘trackName’ is set to string already before pushing, confirmed through console logging… What’s the reference behind “_ref.trackName”? Any help to push me in the right direction would be appreciated. Also, this is my first post to this forum!

AddTrack.js
    import React, {useState} from 'react'
    import {Button, Text, StyleSheet, TextInput, ScrollView} from 'react-native'
    import StateDropDownMenu from '../components/StateDropDownMenu.js'
    import Navbar from '../components/Navbar'
    import Header from '../components/Header'
    import RadioButton from '../components/RadioButton'
    import {Track} from '../../schema'
    import {ObjectId} from 'bson'

    const AddTrack = () => {
      const [trackName, setTrackName] = useState('')
      const [streetAddress, setStreetAddress] = useState('')
      const [city, setCity] = useState('')
      const [state, setState] = useState('default')
      const [zCode, setZcode] = useState('')
      const [trackType, setTrackType] = useState('standard')
      const [availability, setAvailability] = useState('')

      const RBdata = [
        {key: 1, value: 'Standard'},
        {key: 2, value: 'Non-standard'},
      ]

      const onSubmit = async e => {
        let _id = ObjectId()
        let zipCode = parseInt(zCode)
        console.log(`track ID: ${JSON.stringify(_id)}`)
        console.log(`track name: ${trackName} type: ${typeof trackName}`)
        console.log(`street address: ${streetAddress}`)
        console.log(`city: ${city}`)
        console.log(`state: ${state}`)
        console.log(`zip code: ${zipCode}`)
        console.log(`Track type: ${trackType}`)
        console.log(`Availability: ${availability}`)
        try {
          // Create a newTrack object to add to the database using the info on state
          const newTrack = {
            _id,
            trackName,
            streetAddress,
            city,
            state,
            zipCode,
            trackType,
            availability,
          }
          // Open up the database so we can write to it.

          const realm = await Realm.open({schema: [Track]})

          // Now it's time to add the track to the database.

          realm.write(() => {
            realm.create('Track', newTrack)
          })
          alert('Track added!')
        } catch (err) {
          console.warn(err)
        }
      }

      return (
        <ScrollView style={styles.mainView}>
          <Header />
          <Text
            style={{
              textAlign: 'center',
              fontWeight: 'bold',
              fontSize: 30,
              marginBottom: 30,
            }}>
            LET'S ADD A NEW TRACK!
          </Text>
          <Text style={{fontSize: 20}}>Track Name</Text>
          <TextInput
            required='true'
            autoCapitalize='none'
            style={{
              fontSize: 20,
              margin: 10,
              backgroundColor: 'white',
              width: 300,
            }}
            placeholder='My New Track'
            onChangeText={setTrackName}
            value={trackName}
          />
          <Text style={{fontSize: 20}}>Street Address</Text>
          <TextInput
            required='true'
            textContentType='fullStreetAddress'
            style={{
              fontSize: 20,
              margin: 10,
              backgroundColor: 'white',
              width: 300,
            }}
            placeholder='Address goes here'
            onChangeText={setStreetAddress}
            value={streetAddress}
          />
          <Text style={{fontSize: 20}}>City</Text>
          <TextInput
            required='true'
            textContentType='addressCity'
            style={{
              fontSize: 20,
              margin: 10,
              backgroundColor: 'white',
              width: 300,
            }}
            placeholder='City'
            onChangeText={setCity}
            value={city}
          />
          <Text style={{fontSize: 20}}>State</Text>
          <StateDropDownMenu />
          <Text style={{fontSize: 20}}>Zip Code</Text>
          <TextInput
            required='true'
            textContentType='postalCode'
            keyboardType='numeric'
            style={{
              fontSize: 20,
              margin: 10,
              backgroundColor: 'white',
              width: 125,
            }}
            placeholder='30000-1111'
            onChangeText={setZcode}
            value={zCode}
          />
          <Text style={{fontSize: 20}}>Track Type</Text>
          <RadioButton data={RBdata} onSelect={value => setTrackType(value)} />
          <Text style={{fontSize: 20}}>Availability Notes</Text>
          <TextInput
            style={{
              fontSize: 20,
              margin: 10,
              backgroundColor: 'white',
              width: 300,
            }}
            multiline
            placeholder='Enter track availability notes here...'
            onChangeText={setAvailability}
            value={availability}
          />

          <Button
            title='CREATE TRACK'
            onPress={() => {
              onSubmit()
            }}
          />
          <Navbar />
        </ScrollView>
      )
    }

    const styles = StyleSheet.create({
      mainView: {
        flex: 1,
        // alignItems: 'center',
        backgroundColor: 'rgb(206, 234, 234)',
      },
    })

    export default AddTrack

schema.js
    import {ObjectId} from 'bson'

    class Track {
      /**
       *
       * @param {string} name The name of the track
       * @param {string status The status of the task. Default value is "Open"
       * @param {ObjectId} id The ObjectId to create this task with
       */
      constructor ({
        trackName,
        partition,
        streetAddress,
        city,
        state,
        zipCode,
        trackType,
        availability,
        id = new ObjectId(),
      }) {
        this._partition = partition
        this._id = id
        this.trackName = trackName
        this.streetAddress = streetAddress
        this.city = city
        this.state = state
        this.zipCode = zipCode
        this.trackType = trackType
        this.availability = availability
      }
      static schema = {
        name: 'Track',
        properties: {
          _id: 'objectId',
          _partition: 'string?',
          trackName: 'string',
          streetAddress: 'string',
          city: 'string',
          state: 'string',
          zipCode: 'int',
          trackType: 'string',
          availability: 'string',
        },
        primaryKey: '_id',
      }
    }

    export {Track}

    class User {
      /**
       *
       * @param {string} name The name of the task
       * @param {string status The status of the task. Default value is "Open"
       * @param {ObjectId} id The ObjectId to create this task with
       */
      constructor ({
        username,
        partition,
        password,
        email,
        homeCity,
        state,
        id = new ObjectId(),
      }) {
        this._partition = partition
        this._id = id
        this.username = username
        this.password = password
        this.email = email
        this.homeCity = homeCity
        this.state = state
      }
      static schema = {
        name: 'User',
        properties: {
          _id: 'objectId',
          _partition: 'string?',
          username: 'string',
          password: 'string',
          email: 'string',
          homeCity: 'string',
          state: 'string',
        },
        primaryKey: '_id',
      }
    }

    export {User}

:man_facepalming: Looks like code formatting got screwed up a bit… why is there no ‘edit post’ feature?

There is editing - it’s the little pencil icon at the bottom right of the post.

It’s not showing on my UI, no idea why.

That’s darn odd - perhaps something is not set correctly in your account.

I flagged the post to bring attention to it so hopefully someone at Mongo will be able to look at it. The issue could be something super simple, but I am not seeing anything. Sorry for the trouble.

Welcome to the MongoDB Community Forums @Lawgiver2!

Posts from new users have a lower edit time limit as unfortunately spammers have been abusing this feature. As you spend more time in the community you will earn higher trust levels and more forum privileges.

You hopefully won’t see much spam in our forums as we are proactive about preventing and removing, but if you see a post that needs moderator help (including formatting) please flag for moderator attention and we’ll help out. Thanks for flagging this topic, @Jay!

Regards,
Stennie

@Stennie_X Thanks for the explanation and updating the post. All that’s well and good, but does anybody have some insight for my topic? Kind of at a BE standstill until I can resolve.

Hello @Lawgiver2 , did you find a solution?

G’day Folks @Lawgiver2, @Raymond_Michael,

I acknowledge the time since you asked this question.

I hope you have been able to find a solution to this. If not, and for the others who have stumbled upon this.

Option 1: To remove the constructors entirely from your schema:

import {ObjectId} from 'bson';

class Track {
  static schema = {
    name: 'Track',
    properties: {
      _id: 'objectId',
      _partition: 'string?',
      trackName: 'string',
      streetAddress: 'string',
      city: 'string',
      state: 'string',
      zipCode: 'int',
      trackType: 'string',
      availability: 'string',
    },
    primaryKey: '_id',
  };
}

export {Track};

class User {
  static schema = {
    name: 'User',
    properties: {
      _id: 'objectId',
      _partition: 'string?',
      username: 'string',
      password: 'string',
      email: 'string',
      homeCity: 'string',
      state: 'string',
    },
    primaryKey: '_id',
  };
}

export {User};

Option 2: In the current code, if you add .schema after the schema class name, as shown in Tutorial.

Change the code statement
const realm = await Realm.open({schema: [Track]});
to
const realm = await Realm.open({schema: [Track.schema]});

I hope this helps resolve your issue. Please feel free to ask if you have more questions.

Cheers, :performing_arts:

2 Likes