Ryan Prentiss
Ryan Prentiss

Reputation: 1642

Vue FireStore Reactive Key Assignment - Object is possibly 'undefined'

I am attempting to assign FireStore data(), forwarded by props, to a reactive() proxy object, but am receiving the following error:

Object is possibly 'undefined'.
(property) fireStoreData: Record<string, any> | undefined

I wish to use a forEach loop instead of direct assignments i.e. (pageForm.name = props.fireStoreData?.name) to minimize code.

props: {
    fireStoreData: Object,
}
...
setup(props){
    ...
    const pageForm: { [key: string]: any } = reactive({
        name: '',
        address: '',
        ...
    })

    onMounted(() => {
        Object.keys(pageForm).forEach(key => {
            if(key in props.fireStoreData)                  // <-- error found here
                pageForm[key] = props.fireStoreData[key]    // <-- and here
            })
        })
    })
    ...
}

Upvotes: 0

Views: 44

Answers (1)

Ian
Ian

Reputation: 461

The issie is that the fireStoreData prop is not required yet in your code you assume it is.

try:

props: {
    fireStoreData: {
        required: true,
        type: Object
    }
}

If you dont want the prop to be required, its always possible to check for it being defined and add a watcher to look for changes.

Also, dont forget props can change in value.

// on mobile, will format later on pc

Upvotes: 1

Related Questions