Nizar
Nizar

Reputation: 722

Why am I getting TypeError: _this.props."functionName" is not a function ReactJS

So I have the following scripts, it has been a while since I edited them but as far as I can remember they were working flawlessly last time I checked. But now, for some reason the editProfile function has stopped working. I was thinking it was a binding issue but I can't seem to figure out the answer. I tried adding the function to the script itself instead of importing it from authActions but still, that did not work. So in short the issue is in the following piece of code (the following excerpt is from the second script posted below)

handleSubmit = (e) => {
            e.preventDefault();
            this.props.editProfile(this.state);
            this.props.onClose()

        }

both edit profile and onClose are not working. The error is listed below. Both functions throw the same error. In other words if I remove 'this.props.editProfile(this.state);' I'll get the same error for 'this.props.onClose()'

import {storage} from 'config/fbConfig';
import {toastr} from 'react-redux-toastr'

export const signIn = (credentials) => {
  return (dispatch, getState, {getFirebase}) => {
    const firebase = getFirebase();

    firebase.auth().signInWithEmailAndPassword(
      credentials.email,
      credentials.password
    ).then(() => {
      dispatch({ type: 'LOGIN_SUCCESS' });
      toastr.success('ברוכים הבאים לאתר שותפים')
      }).catch((err) => {
      dispatch({ type: 'LOGIN_ERROR', err });
      toastr.error('אירעה שגיאת אימות.')
    });


  }
}

export const signInwithPhoneNumber = () => {
  return (dispatch, getState, {
    getFirebase
  }) => {
   // const firebase = getFirebase();


  }
}



export const signOut = () => {
  return (dispatch, getState, {getFirebase}) => {
    const firebase = getFirebase();

    firebase.auth().signOut().then(() => {
      dispatch({ type: 'SIGNOUT_SUCCESS' })
    });
  }
}

export const signUp = (newUser) => {
  return (dispatch, getState, {getFirebase, getFirestore}) => {
    const firebase = getFirebase();
    const firestore = getFirestore();

    firebase.auth().createUserWithEmailAndPassword(
      newUser.email, 
      newUser.password
    ).then(resp => {
      return firestore.collection('Partners').doc(resp.user.uid).set({
        displayName: newUser.displayName,
        phoneNumber: newUser.phoneNumber,
        email: newUser.email,
        location: null,
        displayImage: "https://wattleparkkgn.sa.edu.au/wp-content/uploads/2017/06/placeholder-profile-sq.jpg",

      });
    }).then(() => {
      dispatch({ type: 'SIGNUP_SUCCESS' });
      //dispatch(send_EmailVerification())
    }).catch((err) => {
      dispatch({ type: 'SIGNUP_ERROR', err});
    });
  }
}

export const editProfile = (profile) => {
  return (dispatch, getState, {
    getFirebase, getFirestore
  }) => {
    const firestore = getFirestore();
      const Puid = getState().firebase.auth.uid;
      if (profile.uploadedImages !== ''){
       const uploadedImages = profile.uploadedImages
            const uploadTask = storage.ref(`images/${uploadedImages.name}`).put(uploadedImages);
            uploadTask.on('state_changed',
                (snapshot) => {
                    // progrss function ....
                    const progress = Math.round((snapshot.bytesTransferred / snapshot.totalBytes) * 100);
                    console.log(progress);
                },
                (error) => {
                    // error function ....
                    console.log(error);
                },
                () => {
                    // complete function ....
                    storage.ref('images').child(uploadedImages.name).getDownloadURL().then(url => {
                      // displayImage = url;

                      firestore.collection('Partners').doc(Puid).set({
                        displayName: profile.displayName,
                        phoneNumber: profile.phoneNumber,
                        location: profile.location,
                        displayImage: url

                      }).then(() => {
                        toastr.success('הודעה', 'הפרופיל עודכן בהצלחה')
                        dispatch({
                          type: 'EDIT_PROFILE_SUCCESS'
                        })

                      }).catch(function (error) {
                        // An error happened.
                        dispatch({
                          type: 'EDIT_PROFILE_ERROR'
                        })
                        toastr.error('אופס! אירעה תקלה :|')
                      });
                    })
                });
              }
              else{

                 firestore.collection('Accounts').doc(Puid).set({
                   ...profile,
                   displayName: profile.displayName,
                   phoneNumber: profile.phoneNumber,
                   location: profile.location,
                   displayImage: profile.displayImage

                 }).then(() => {
                   dispatch({
                     type: 'EDIT_PROFILE_SUCCESS'
                   })
                   toastr.success('הודעה', 'הפרופיל עודכן בהצלחה')
                 }).catch(function (error) {
                   // An error happened.
                   dispatch({
                     type: 'EDIT_PROFILE_ERROR'
                   })
                   toastr.error('אופס! לא יכולנו לעדכן את הפרופיל')
                 });
              }



  }
}

export const send_EmailVerification = () => {
  return (dispatch, getState, {getFirebase}) => {
    const firebase = getFirebase();

    firebase.auth().currentUser.sendEmailVerification().then(() => {
      //email send
      dispatch({ type: 'EMAIL_VERIFICATION_SUCCESS' })
      toastr.info('הודעה', 'הודעת אימות נשלחה למייל')
    }).catch(function (error) {
      // An error happened.
      toastr.error('The message')
    });;
  }
}

This is the buildProfile script that needs to use "editProfile" function from above script.

import React, { Component } from 'react'
import 'assets/css/Css.css'
import {editProfile} from 'store/actions/authActions'




import { Button,Icon} from 'react-materialize';

import GridContainer from "components/Grid/GridContainer.jsx";
import GridItem from "components/Grid/GridItem.jsx";
import Card from "components/Card/Card.jsx";
import withStyles from "@material-ui/core/styles/withStyles";



import { connect } from 'react-redux'
import { firestoreConnect } from 'react-redux-firebase'
import { compose } from 'redux'
import { Hidden } from '@material-ui/core';

import $ from 'jquery';
import 'react-redux-toastr/lib/css/react-redux-toastr.min.css'
import Properties from 'components/Profile/properties'

import { clearSelectedProperty } from "../../store/actions/propertyActions";

// @material-ui/icons

class BuildProfile extends Component {
    state = {
        displayName: (this.props.profile !== null) ? this.props.profile.displayName : '',
        location: (this.props.profile !== null) ? this.props.profile.location : '',
        displayImage: (this.props.profile !== null) ? this.props.profile.displayImage : '',
        phoneNumber: (this.props.profile !== null) ? this.props.profile.phoneNumber : '',
        uploadedImages: '',
        file:''
     }

    handleChange = (e) => {
        this.setState({
            [e.target.id]: e.target.value
        })
    }

    handleImagesUpload = (e) => {
        if (e.target.files) {
            const uploadedImages = e.target.files[0]
            const file =  URL.createObjectURL(e.target.files[0])
            this.setState(() => ({
                uploadedImages,
                file
            }));
        }
    }

    handleSubmit = (e) => {
        e.preventDefault();
        this.props.editProfile(this.state);
        this.props.onClose()

    }
    handleSelectChange = (e) => {
        this.setState({
            location: e.target.value
        })
    }

    render() {

        const {profile, onClose} = this.props;
        const {
            displayName,
            location, displayImage, phoneNumber
        } = this.state
        const locationOptions = [
            {label: "תל אביב", value: 'תל אביב', type: "location"},
            {label: " ירושליים ", value: 'ירושליים', type: "location"},
            {label: "חיפה", value: 'חיפה', type: "location"}
        ];
        //if (auth.uid) return <Redirect to='/' />

        return (

            <GridContainer  justify="center">
                <GridItem xs={13} sm={12} md={4}>
                <Card >

<form onSubmit={this.handleSubmit}>
                        <div className="modal-header"><h3 style={{marginRight:-17}} className='center-align'>יצרירת פרופיל</h3></div>
                        <div className="modal-content" style={{padding:"6rem",marginTop:-40}}>
                        <div className="col s5 m4 l3 center">

                                    <img className="profile-pic circle" height="150" style={{maxWidth:200,marginTop:-25}}
                                         src={this.state.uploadedImages? this.state.file :  "https://wattleparkkgn.sa.edu.au/wp-content/uploads/2017/06/placeholder-profile-sq.jpg"}
                                         alt="profile pic"

                                         />

                                         {console.log(this.state.file)}
                                         <div className="row">

                                                                                     <input type="file" id="uploadedImages" onChange={this.handleImagesUpload}  style={{marginRight:38,maxWidth:150,overflowX:"auto"}}/>
                                                                                     </div>
                                </div>
                            <div className="row">


                                    <div className="input-field" style={{width:300}}>
                                        <input id="displayName" type="text" className="validate"

                                        placeholder={null}

                                               value={this.props.displayName}
                                               onChange={this.handleChange}/>
                                        <label className="active" htmlFor="displayName">שם מלא</label>
                                    </div>


                            </div>
                            <div className="row" style={{marginTop:-10}}>
                                    <div className="input-field" style={{width:300}}>
                                        <input id="phoneNumber" type="text" className="validate"
                                               value={profile.phoneNumber}
                                               onChange={this.handleChange}/>
                                        <label className="active" htmlFor="phoneNumber">מס׳ טלפון</label>
                                    </div>
                                </div>

                                <div className="col s12 m6 input-field">

                                    <select id="location" style={{display:"block", marginRight:-10}}
                                            onChange={this.handleSelectChange}
                                            value={null}
                                            required>
                                        <option value="" disabled defaultValue>Location
                                        </option>
                                        {locationOptions.map(function (option) {
                                            return <option key={option.value}
                                                           value={option.value}>{option.label}</option>
                                        })}
                                    </select>
                                    <label style={{marginTop:-37,marginRight:-10, fontSize:"12px"}}>איזור</label>

                                </div>
                                <div className="col s12 m6 input-field" style={{marginTop:30,marginRight:60}}>
                        <Button type="submit" waves="light" style={{backgroundColor:"#ff6969"}}>
המשך
</Button>

             </div>

         </div>




                    </form>
                    </Card>

                    </GridItem>
                            </GridContainer>

        )
    }
}

const mapStateToProps = (state, props) => {
    console.log(state,props)
     return {
       authError: state.auth.authError,
       auth: state.firebase.auth,
       properties: state.firestore.ordered.Properties,
       partner: state.firestore.ordered.Partners,
       profile: state.firebase.profile,
       selectedProperty: state.property,
       invitation: state.firestore.ordered.Invitations

     }

   }

   const mapDispatchToProps = (dispatch) => {
     return {

     }
   }

   export default compose(

     connect(mapStateToProps, mapDispatchToProps),
     firestoreConnect((props) => {
         if (!props.auth.uid) {
           props.history.push('/signin')
           return []
         }
         let propid = null
            if(props.invitation !== undefined){
                propid = props.invitation[0].propid
            }
            return [
             {
               collection: 'Invitations',
              doc: props.match.params.inviteid

             },
             {
               collection: 'Partners',
               doc: props.auth.uid
             },
             {
                 collection: 'Properties',
                 doc: propid
             },

           ]
        }

    )
    )(BuildProfile)   

I keep getting the following error

enter image description here

Upvotes: 0

Views: 1168

Answers (1)

rMonteiro
rMonteiro

Reputation: 1696

BuildProfile component does not have a prop editProfile in props or it is not a function. I see you are importing the editProfile function:

import {editProfile} from 'store/actions/authActions'

Probably you want to call editProfile like this:

handleSubmit = (e) => {
            e.preventDefault();
            editProfile(this.state);
            onClose();
}

Upvotes: 1

Related Questions