Utilize Express to update user data stored in MongoDB

Greetings everyone! I've been attempting to develop an update function for my app, but unfortunately, I encountered an error that states

getState is not a function. (In 'getState()','getState' is 'Stephanson')
, which refers to the lastName value.

Let me share the update controller code snippet from Authentication_controller.js on the backend:

// Update user data
exports.update = function (req, res, next) {
  res.json({ data: req.user });
}

Additionally, here is the router code snippet from the backend:

router.route('/users/:user_id/data')
  .put(requireAuth, AuthenticationController.update);

Furthermore, here is the update action from userActions.js:

export function updateUserData(dispatch, getState) {
  const state = getState();
  const {user_id, token} = state.auth;
    return axios.put(USER_DATA(user_id), {
      headers: { authorization: token }
    }).then((response) => {
      console.log('my data = ' + response.data.data.userData[0].firstName);
      dispatch(setUserData(response.data.data.userData[0]));
    }).catch((err) => {
      dispatch(console.log("Couldn't update user data."));
    });
}

export var setUserData = (userData) => {
  return {
    type: 'SET_USER_DATA',
    userData
  }
}

Moving on, here is the content of userDatareducer.js:

module.exports = (state = [], action) => {
  switch (action.type) {
    case 'SET_USER_DATA':
      return action.userData;

    case 'UPDATE_USER_DATA':
      return action.userData;

    default:
      return state;
  }
}

Lastly, here is how FullName.js page looks like where I am utilizing Wizard Form from Redux Form:

const onSubmit = (values, dispatch) => {
    console.log(values);
    const firstName = values.firstName;
    const lastName = values.lastName;
    dispatch(updateUserData(firstName, lastName));
};
const FullName = props => {
    const { handleSubmit } = props;
    return (
        <View style={{ flex: 1 }}>
            <ScrollView style={{ backgroundColor: '#ffffff' }}>
                <View style={{ flex: 1, flexDirection: 'column', marginTop: 0, margin: 40 }}>
                    <Text style={{ fontSize: 40, marginTop: 60 }}>Full Name</Text>
                    <Text style={{ fontSize: 20, marginTop: 10 }}>Can you please tell your name?</Text>
                    <View style={{ marginTop: 100 }}>
                        <Field keyboardType='default' label='First Name' component={renderFieldFn} name='firstName' />
                        <Field keyboardType='default' label='Last Name' component={renderFieldLn} name='lastName' />
                    </View>
                </View>
            </ScrollView>
            <TouchableHighlight onPress={handleSubmit(onSubmit)} style={{ backgroundColor: 'white', padding: 20, alignItems: 'center' }}>
                <Text style={{
                    backgroundColor: 'black', color: 'white', fontSize: 20, fontWeight: 'bold',
                    height: 50, width: 300, textAlign: 'center', padding: 14
                }}>NEXT</Text>
            </TouchableHighlight>
        </View>
    );
}
export default reduxForm({
    form: 'newUser',
    destroyOnUnmount: false,
    forceUnregisterOnUnmount: true,
    validate
})(FullName)

Answer №1

Make a small tweak in userActions.js by switching

export function updateUserData(dispatch, getState) {

to

export const updateUserData = (firstName, lastName) => (dispatch, getState) => {

When using redux-thunk, the return value is a function that creates an action. This adjustment is similar to the example provided in the documentation:

function incrementIfOdd() {
  return (dispatch, getState) => {
    const { counter } = getState();

    if (counter % 2 === 0) {
      return;
    }

    dispatch(increment());
  };
}

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

Option to Exclude Files in Gulp-uncss

I've been trying to use the ignore option, but it doesn't appear to be functioning as expected. My code looks like this: .pipe(plugins.uncss({ html: glob.sync('./**/*.{csh,h}tml'), ignore: ['.active'] ...

An array is not just a mere collection of elements

I have an object that resembles an array var items = [ { started_time: 2017-05-04T12:46:39.439Z, word: 'bottle', questionId: '161013bd-00cc-4ad1-8f98-1a8384e202c8' }, { started_time: 2017-05-04T12:47:26.130Z, word: &apo ...

"Trouble connecting Sequelize associations with API routes, resulting in unsuccessful retrieval of data from the database

I am currently navigating the complexities of sequelize and express, facing challenges with database associations and data retrieval. My project involves a boarders-boards (focused on surfboards and riders) database with three main models: Boards, Riders, ...

Comparison between event.target and event.relatedTarget for event handling

I am curious about the distinction between event.target and event.relatedTarget. Here is a snippet of code I came across in a drag and drop activity: ondragleave: function (event) { // removing the drop feedback style event.target.classList.re ...

How to Stop AJAX Requests Mid-Flight with JQuery's .ajax?

Similar Question: Stopping Ajax Requests in JavaScript with jQuery Below is the straightforward piece of code that I am currently using: $("#friend_search").keyup(function() { if($(this).val().length > 0) { obtainFriendlist($(this).va ...

What steps can be taken to fix the issue of "Unable to find view 'list' in the views directory"?

My code contains the following: const express = require("express"); const bodyParser = require("body-parser"); const app = express(); app.set("view engine", "ejs"); app.get("/", function(req, res){ var today = new Date(); var currDay = today.get ...

You should be providing a string value as expected. It seems that you may have overlooked exporting your component from the correct file it was defined in, or perhaps there is confusion with default and named

I encountered a strange error despite meticulously organizing and exporting/importing files. The code is structured from components to the App render method. Item.js import React from 'react'; import './Global.css' const Item = ({data ...

Executing multiple operations with Graphql mutations

I am faced with a situation where I have 3 mutations to execute with 6 input parameters each. I need to send a mutation based on the value of certain status variables. How can I achieve this efficiently? mutation updateProfile( $input: UpdateProfileMuta ...

jQuery show/hide functionality allows you to toggle the visibility of elements

I am looking to create a toggle button that expands the menu-wrapper width and hides the sidebar when clicked. Here is the initial CSS styling: #my-wrapper { Width:500px; } #sidebar-wrapper { width:200px; } Upon clicking the button, the CSS will update ...

Develop a JavaScript function to declare variables

I am currently attempting to develop a small memory game where the time is multiplied by the number of moves made by the player. Upon completion of all pairs, a JavaScript function is executed: function finish() { stopCount(); var cnt1 = $("#cou ...

What is the best way to update a React state with JSON data?

Currently, I am dealing with a React component that sends a post request to an Express server hosted by myself. The server employs web3 for signing transactions on the Ethereum blockchain. Upon successful inclusion of the transaction in a block, a JSON obj ...

Reached the maximum number of iterations for Angular 10 $digest() function

Currently, I am following a MEAN stack tutorial on Thinkster and encountering an issue with my Angular factory service. Angular.js:11598 Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting! Watchers fired in the last 5 iterations: [] H ...

What is the best way to implement object-oriented programming to have an asynchronous AJAX request return a value upon completion?

I need assistance with the code snippet provided below. My goal is for the 'airported' object to generate a list of airports. However, I am struggling to retrieve the data once the each loop has completed its iteration in finding 'li's ...

Error in Safari Browser: Unexpected token ':' found in AngularJS syntax

When using Chrome, my website works perfectly without any errors. However, when I try to access it on Safari, most of the pages fail to load. The specific error message that appears is: [Error] SyntaxError: Unexpected token ':' (angular.min.js.m ...

Update the ng-model in AngularJS when the value is set to true

Hello there, I am in the process of developing an app that provides a summary of data from a database. In this app, there is a form that populates input fields with information using ng-model. Users can edit these values as needed. However, I want to ensu ...

Building a personalized payment experience using Python Flask and Stripe Checkout

I'm attempting to set up a customized checkout integration with Stripe on my Flask web application and I've encountered some issues. After copying the code from the Stripe documentation (located at https://stripe.com/docs/checkout#integration-cu ...

Connection details for SQL server on local Prisma app

Attempting to establish a connection to a local SQL server from an Express JS app using Prisma with the following URLs: DATABASE_URL="sqlserver://localhost:1433;database=test;user=dummy;password=dummy;trustServerCertificate=true" DATABASE_URL=&qu ...

Simplified React conditional rendering made easy

Currently, I am utilizing React 16 with Material-Ui components. In my root component, I have a requirement to load a tab and a view conditionally based on a property. Although I have managed to implement this functionality, the code appears quite messy a ...

Words next to picture

Can someone help me with aligning different images of varying widths but the same height inline with text next to each image? I tried to do it, but it doesn't look good on responsive screens. Any suggestions on how to fix this? And if there's a b ...

Can you please explain the purpose of this function?

I came across this code snippet on a website and I'm curious about its function and purpose. While I'm familiar with PHP, HTML, CSS, and JavaScript, I haven't had the chance to learn JQUERY and AJAX yet. Specifically, I'm interested in ...