3

I have created a form with email, firstname, lastname details. Now I want to make a POST request to localhost:5000/api/users and want to store it in mongo database. How can I make use of redux ? I have implemented it using on reactjs only how can I make use of redux ? Note: I am using redux thunk.

Code:

login.js:

import React, { Component } from 'react'
import './login.css'

export default class Login extends Component {

  constructor(props) {
    super(props)
    this.state = {
      firstName:'',
      lastName:'',
      email:''
    }

    this.onChangeHandler = this.onChangeHandler.bind(this)
    this.onSubmitHandler = this.onSubmitHandler.bind(this)
  }

  onChangeHandler(e){
    this.setState({ [e.target.name]: e.target.value })
  }

  onSubmitHandler(e){
    e.preventDefault();
    console.log(this.state)
  }

  render() {
    return (
      <div>
        <form onSubmit={this.onSubmitHandler}>
          <label>
            FirstName:
            <input type="text" name="firstName" value={this.state.firstName} onChange={this.onChangeHandler} />
          </label>

          <label>
            LastName:
            <input type="text" name="lastName" value={this.state.lastName} onChange={this.onChangeHandler} />
          </label>

          <label>
            Email:
            <input type="text" name="email" value={this.state.email} onChange={this.onChangeHandler} />
          </label>
          <button type="submit" className="btn btn-default">Submit</button>
        </form>
      </div>
    )
  }
}

loginAction.js:

import { ADD_USER } from './types';
import axios from 'axios';

export const userLoginRequest = () => dispatch => {
    axios.post(`localhost:5000/api/users`)
    .then( userdata => 
        dispatch({
            type: ADD_USER,
            payload: userdata
        })
    )
    .catch( error => {
        console.log(error);
    });
};

loginReducer.js:

import { ADD_USER } from '../actions/types';

const initialState = {
    firstName: '',
    lastName: '',
    email: ''
}


export default function (state = initialState, action) {
    switch (action.type) {
        case ADD_USER:
            return {
                ...state,
                items: action.payload
            };
        default:
            return state;
    }
}

I am not able to understand do I need to create 3 actions each one for firstname, lastname and email ? In that case what will be those 3 actions will it have 3 POST req in each of them ?

2
  • I suggest you read about Thunk and middleware in order to achieve asynchronous code in Redux. Commented Nov 1, 2018 at 11:59
  • @RonF I have read it now I need some help in organizing the code. I am not able to understand how to implement loginUser using react redux by making POST req to localhost:5000/api/users Commented Nov 1, 2018 at 12:01

1 Answer 1

6

I recommend you to have some insight about redux and redux-thunk. For making network requests you need to use middleware like redux-thunk or redux-saga;

Here are very basic examples of redux-thunk

//example 1
function myThunkActionCreator(someValue) {
    return (dispatch, getState) => {
        dispatch({type : "REQUEST_STARTED"});

        myAjaxLib.post("/someEndpoint", {data : someValue})
            .then(
                response => dispatch({type : "REQUEST_SUCCEEDED", payload : response}),
                error => dispatch({type : "REQUEST_FAILED", error : error})
            );    
    };
}

// example 2 for conditional dispatching based on state
const MAX_TODOS = 5;

function addTodosIfAllowed(todoText) {
    return (dispatch, getState) => {
        const state = getState();

        if(state.todos.length < MAX_TODOS) {
            dispatch({type : "ADD_TODO", text : todoText});
        }    
    }
}

Update

So the flow for posting the form data to the server using redux-thunk goes like so

  1. When submit button is clicked and action gets dispatched let us suppose SAVE_USER_TO_SERVER and an object with all the user details (name, email etc) is passed to for eg postUserThunkCreator() (which is a thunk function like in examples above).

  2. Then thunk makes a post request to the server and sends the data along with it. And on the server side it gets saved into the database and response is returned

  3. Now myAjaxLib.post("/someEndpoint", {data : someValue}).then() in .then() function you can check for the response if successfull the dispatch another action for eg SAVE_USER_TO_SERVER_SUCCESS otherwise SAVE_USER_TO_SERVER_FALIURE;

*So as we can see that three actions are bieng dipatched in this work flow namely : SAVE_USER_TO_SERVER

SAVE_USER_TO_SERVER_SUCCESS

SAVE_USER_TO_SERVER_FALIURE

So I hope its clear to you that you to create three action mentioned above.

Your Question Do I need to create 3 actions each one for firstname, lastname and email ?

Answer: Not at all. Only three action mentioned above.

Sign up to request clarification or add additional context in comments.

7 Comments

I want to ask you. Should I create 3 actions i.e for firstname, lastname, email ? And then reducer will have 3 action types am I right ? Can you add it in your answer.
ok let me edit the answser to add the redux flow for post request
If 3 actions are not required then how will I get email, firstname, lastname ? As the initialstate for all of them is "" So should I also create user object inisde initialstate ? I am not able to understand how will the reducer and actions will look like ?
Yes you should use user = {} in initialState and when the user is successfully saved SAVE_USER_TO_SERVER_SUCCESS update the user in store.
and when you will call action creator for eg postUserThunkCreator() you will pass the user info to actionCreator like so postUserThunkCreator(this.state.firstName, this.state.lastName, etc) in your case. Or if u take all fields in a single user object then simply postUserThunkCreator(this.state.user)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.