Prop function not being recognized when passed down to another component

When retrieving my access_token's payload, I am including a significant amount of profile information such as user details and bio data

{
  "token_type": "access",
  "exp": ***,
  "iat": ***,
  "jti": "*****",
  "user_id": 1,
  "username": "emmanuelS21",
  "first_name": "",
  "last_name": "",
  "country": "",
  "city": "",
  "bio": "",
  "photo": "\"profile/2022/03/27/emmanuelpic.png\""
}

This data is then utilized to populate a user's profile page. I am currently in the process of creating a feature that allows users to update their profile details by submitting a form with new information. However, I keep encountering an error message:

Uncaught TypeError: updateProfile is not a function

The function updateProfile should handle the logic for updating profile information. Below are snippets of the relevant code:

Profile.js:

import { updateProfile } from "../login_components/LoginActions.js";

    const Profile = () => {
        let { user,logOutUser,updateProfile } = useContext(AuthContext)
        const[profileUser, setProfileUser] = useState({user})
        //handle form submission
        const handleSubmit = e => {
            console.log('handle submit',profileUser)
            const updatedProfile = {
                username: profileUser.username,
                email: profileUser.email,
                first_name: profileUser.first_name,
                last_name: profileUser.last_name,
                city: profileUser.city,
                country: profileUser.country
            }
            e.preventDefault();
            updateProfile(updatedProfile);
    }

My LoginTypes.js:

export const SET_TOKEN = "SET_TOKEN";
export const SET_CURRENT_USER = "SET_CURRENT_USER";
export const UNSET_CURRENT_USER = "UNSET_CURRENT_USER";
export const UPDATE_PROFILE = "UPDATE_PROFILE";

LoginActions.js:

export const updateProfile = (userData) => dispatch => {
    axios
        .post("http://127.0.0.1:8000/update_profile/", userData)
        .then(response => {
            console.log('response is:', response.data)
            dispatch({
                type: UPDATE_PROFILE,
                payload: userData
  });
        })

}

UPDATE made changes based on the top answer, added my updateProfile function to my AuthContext file

   const updateProfile = (userData) => dispatch => {
        console.log('Update Profile is being triggered')
        axios
            .put('http://127.0.0.1:8000/update_profile/', userData)
            .then(res => {
                console.log(res)
            })
    }
    let logOutUser = () => {
        setAuthTokens(null)
        setUser(null)
        localStorage.removeItem('authTokens')
        history.push('/')
    }

and avoided overwriting this function in Profile.js:

let { user,logOutUser,updateProfile } = useContext(AuthContext)
        const[profileUser, setProfileUser] = useState({user})
        const handleSubmit = e => {
            console.log('handle submit',profileUser)
            const updatedProfileInfo = {
                username: profileUser.username,
                email: profileUser.email,
                first_name: profileUser.first_name,
                last_name: profileUser.last_name,
                city: profileUser.city,
                country: profileUser.country
            }
            console.log(updatedProfileInfo)
            e.preventDefault();
            updateProfile(updatedProfileInfo);

however, the error persists despite these adjustments

Answer №1

By destructuring the useContext call and overwriting updateProfiles, you are causing it to become undefined since it most likely does not exist on the returned object. This results in an error being thrown.

//       not called because it is shadowed
import { updateProfile } from "../login_components/LoginActions.js";

// ...
        let { user, logOutUser, updateProfile } = useContext(AuthContext);
                                          ^
        // ...                            |
                                          | // refers to this which is undefined
        updateProfile(updatedProfile); <--|
// ...

If you remove the updateProfile assignment, the issue should be resolved:

import { updateProfile } from "../login_components/LoginActions.js";
         |
// ...____
      |  let { user, logOutUser } = useContext(AuthContext);
      |                                   
      |  // ...                            
      |                                   
      |->updateProfile(updatedProfile);
// ...

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I utilize an external file in Node js to output as a response?

I came across a similar inquiry, but I am interested in exploring manual methods. My goal is to achieve this without relying on express or any other external library. var http = require('http'); var server = http.createServer(function(req, res) ...

Attempting to implement an EventListener to alter the navbar upon scrolling, unsuccessful at the moment

Exploring ways to update the navigation bar upon scrolling to shrink its size and modify the color scheme (specifically, transitioning from a transparent background to white and altering font colors). Below is the HTML snippet: /* Defining the overa ...

I'm currently in the process of creating a snake game using HTML5. Can you help me identify any issues or problems that

I am experiencing an issue where nothing is appearing on the screen. Below are the contents of my index.html file: <html> <body> <canvas id="canvas" width="480" height="480" style="background-color:grey;"></canvas> <script src=" ...

Dynamic rule addition with JQuery Validation

I am searching for a method to dynamically incorporate the jQuery validation rules, as they are needed in various locations. For instance, a user can edit news in two different ways. The first method involves using a standard form with jQuery validation, ...

Rearrange the items in an array that contain different data types

After spending some time searching on SO, I did find some helpful information but I am still struggling to achieve the desired solution. My current issue involves a keypad with numbers 1 through 5. When a number key is selected, it gets added to an array n ...

jQuery is not defined when importing reactjs, bootstrap, and npm modules

Having trouble using Bootstrap in my React app, as I keep getting an error message saying Error: Bootstrap's JavaScript requires jQuery. I've already imported jQuery and tried various solutions found in other posts like: import $ from 'jque ...

Broadcasting Packets Between Node.js Ports

I have a set of server.js and client.js scripts that work in tandem. Below is the server.js script... var express = require('express'); var appMain = express(); var appReset = express(); var serverMain = require('http').Server(appMain ...

What is the best way to change the location of a jQuery Mobile global popup?

I have a jQuery Mobile global popup that is initially empty and generated dynamically. I am utilizing the beforeposition event to detect when the popup opens. At this point, I load a configuration file or content file, create the content, and then add it t ...

Ways to dynamically insert a new row into a table based on user input in a Postman-like reactive table

Is there a way to dynamically insert a row when a single character is entered into an input field in the header tab, similar to how Postman functions? 1) If a user types any single character in the td of the first row, then a new row should be added below ...

After the introduction of ReactiveFormsModule, the functionality of the Angular router has ceased

I am working on setting up a reactive form in Angular for a login page. Here is my login form: <form [formGroup]="loginForm" (ngSubmit)="login(loginForm.value)"> <div class="form-group"> <label for="username">Username</label> ...

Strategies for Applying Filters in Search Feature on IOS Devices

Currently, I have an array of books that are being displayed on my view. At the top of the view, there are 3 filters available: (All | Reading level 1 | Reading Level 2 | Reading Level 3) (All | Informational | Literature) (All | Published in 2000-2005 | ...

VueJS1 flexible $parent.$parent method duration

Trying to utilize a parent function across multiple layers of nested child components. {{ $parent.$parent.testFunction('foo', 'bar') }} This approach currently functions, however, each time I navigate through levels in the hierarchy, ...

What could be causing the information from the ajax call to not appear in this popover?

Hovering over a link will trigger a popover with a 1 second delay containing user profile information, loaded using AJAX. $(function() { var timer = null; var xhr = null; $('.user_popup').hover( function(event) { ...

What steps do I need to take to ensure that my angular application can be displayed properly on Internet Explorer

I am facing an issue with my application not rendering in ie8. I have added all the necessary shim and shiv scripts, but it still doesn't work. The strange thing is that my application runs perfectly on every other browser version above ie9. Any help ...

JavaScript - Executing the change event multiple times

Below is the table I am working with: <table class="table invoice-items-table"> <thead> <tr> <th>Item</th> <th>Quantity</th> <th>Price</th> & ...

The AJAX request is not executing the xmlhttp.open method for running the script

Currently, I am making adjustments to the tutorial available at this website: http://www.w3schools.com/ajax/ajax_aspphp.asp. My modification involves storing a library of autocomplete names in a database. I have implemented a button that allows users to ...

A pattern matching formula to eliminate specific characters from the beginning to the end of a string

I am facing an issue with extracting content from a given string: var string = "From: Sarah<br /> Sent: 10 May 2021 09:45:20</br /> To: Alice<br /> Subject: Meeting Reminder<br /><br /> Hi Alice, <br /> Here is a ...

Exploring the Exciting Possibilities of Combining Rails 4

I feel like I must be doing something really silly or foolish here. I've been banging my head against the wall all day trying to make jQueryUI work in my Rails 4.2.1 application, but for some reason, it's just not happening. It seems like such a ...

Is there a way to display multiple items at once in a bootstrap carousel?

I am currently working on implementing a carousel feature in my React project to display reviews. I have chosen to utilize the bootstrap carousel for this purpose. Here is the carousel that I am using However, I aim to achieve a design similar to this Wi ...

What is the best way to retrieve data from the next page in a Protractor test?

I am currently in the process of automating the test for booking a flight. When I enter the credentials on the homepage, click the Submit button, and the browser navigates to the search results page. const EC = protractor.ExpectedConditions; describe( ...