slukic0 / movies-app

Fullstack MERN application that allows users to browse, search, and favourite movies using the MovieDB API.
https://movies-app.onrender.com/
GNU General Public License v3.0
3 stars 0 forks source link

Showing Error in Adduser.js please help me #15

Open pilli-sukumar opened 1 year ago

pilli-sukumar commented 1 year ago

import { Component } from "react"; import axios from "axios"; import { Redirect } from "react-router-dom"; import { withAuth0 } from "@auth0/auth0-react"; import Spinner from '../Spinner/Spinner'

class AddUser extends Component{

constructor(props){
    super(props)
    this.state={
        loading: false,
        done: false,
        server: process.env.REACT_APP_SERVER_URL || ''
    }
}

addUserToDB = () => {
    const { user, isLoading } = this.props.auth0

    if(!isLoading && !this.state.done){
        const userID = user.sub

        axios.get(this.state.server+`/api/users/exists/${userID}`)
            .then(res => {
                if (!res.data){ // user is not in the DB, lets create a new user
                    const newUser = {
                        identifier: userID,
                        fav_movies: [],
                        email: user.email
                    };
                    axios.post(this.state.server+`/api/users/create`, newUser)
                        .then( () => {
                            console.log('added user')
                        })
                }
            })
            .then( () => {
                this.setState({done: true})
            })
    }
}

componentDidUpdate = () => {
    const { isLoading } = this.props.auth0

    if (isLoading || (!this.state.done && !this.state.loading) ){
        this.setState({loading: true}, () => {
            (this.addUserToDB())
        })
    }
}

render(){       
    if (this.state.done) {
        return(<Redirect to='/'/>);
    }
    else{
        return(<Spinner />)
    }
}

}

export default withAuth0(AddUser);

//Error

Cannot read properties of undefined (reading 'sub') TypeError: Cannot read properties of undefined (reading 'sub') at AddUser.addUserToDB (http://localhost:3000/static/js/bundle.js:2163:29) at AddUser. (http://localhost:3000/static/js/bundle.js:2191:16) at callCallback (http://localhost:3000/static/js/bundle.js:39500:16) at commitUpdateQueue (http://localhost:3000/static/js/bundle.js:39518:13) at commitLayoutEffectOnFiber (http://localhost:3000/static/js/bundle.js:47548:17) at commitLayoutMountEffects_complete (http://localhost:3000/static/js/bundle.js:48662:13) at commitLayoutEffects_begin (http://localhost:3000/static/js/bundle.js:48651:11) at commitLayoutEffects (http://localhost:3000/static/js/bundle.js:48597:7) at commitRootImpl (http://localhost:3000/static/js/bundle.js:50507:9) at commitRoot (http://localhost:3000/static/js/bundle.js:50387:9)

pilli-sukumar commented 1 year ago

Please help me in solving the error