<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Emanuel Raj on Medium]]></title>
        <description><![CDATA[Stories by Emanuel Raj on Medium]]></description>
        <link>https://medium.com/@raju.allen?source=rss-2981354d3021------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Xo4hzABl5beqLdXv8XZ2cw.jpeg</url>
            <title>Stories by Emanuel Raj on Medium</title>
            <link>https://medium.com/@raju.allen?source=rss-2981354d3021------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 08:12:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@raju.allen/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[A Simple CRUD Application On React + Redux + Axios + Nodejs REST API + MongoDB — Part II]]></title>
            <link>https://medium.com/@raju.allen/a-simple-crud-application-with-login-on-react-redux-axios-nodejs-rest-api-mongodb-part-ii-376606eb67a7?source=rss-2981354d3021------2</link>
            <guid isPermaLink="false">https://medium.com/p/376606eb67a7</guid>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[axios]]></category>
            <category><![CDATA[crud]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Emanuel Raj]]></dc:creator>
            <pubDate>Wed, 29 Aug 2018 08:05:27 GMT</pubDate>
            <atom:updated>2019-03-14T06:03:30.564Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*ctFfwgFKSwGu1SYHHQN3-w.jpeg" /></figure><p>In Part 1 of this series we have created Nodejs API’s to perform CRUD operation. If you want to look at part 1 here is the <a href="https://medium.com/@raju.allen/a-simple-crud-application-with-login-on-react-redux-axios-nodejs-rest-api-mongodb-part-i-af9c534251b">link</a>.</p><p>In this Part, we will consume those API’s and build a web Application in React + Redux. Like I said in part 1, the main objective of this two part series is to build the sample application rather than explaining what react is? So let’s get things rolling.</p><p>Let’s create the new react application with create-react-app.</p><pre>$ create-react-app vendor-crud</pre><p>this will basically install all the basic react packages needed to run sample react application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/322/1*4_n5_5e4T7bVx5RHbqDcJw.png" /></figure><p>Your application repository looks something like this.</p><p>Let’s start installing the packages we needed to build our app.</p><ol><li>@material-ui/core — For using Material UI design for our components.</li><li>@material-ui/icons — For using Material UI icons.</li><li>axios — To make API calls.</li><li>classnames —To conditionally join classNames together.</li><li>history — To manage session history.</li><li>prop-types — To type-check for React props.</li><li>react-redux — Library that help React and Redux talk to each other.</li><li>redux — Predictable state container.</li><li>redux-thunk — A middleware for Redux.</li></ol><pre>$ npm install --save <a href="http://twitter.com/material">@material</a>-ui/core <a href="http://twitter.com/material">@material</a>-ui/icons axios classnames history prop-types react-redux redux redux-thunk react-router-dom</pre><p>Let’s create the directories needed for our redux.</p><ol><li>_actions</li><li>_helpers</li><li>_reducers</li><li>_components</li><li>_services</li></ol><p>If you already gained enough knowledge on Redux, you would already know what are actions and reducers are, so I’m not going in deep on those topics. If you don’t know what is Redux and the words actions and reducers look alien to you in the context of redux, I would recommend you to start with this nice <a href="https://medium.freecodecamp.org/understanding-redux-the-worlds-easiest-guide-to-beginning-redux-c695f45546f6">article</a>.</p><p>So, let’s start our react coding with focus on creating routing. We will create a private route and the public route.</p><p>_components/PrivateRoute.jsx</p><pre>import React from &#39;react&#39;;<br>import { Route, Redirect } from &#39;react-router-dom&#39;;</pre><pre>export const PrivateRoute = ({ component: Component, ...rest }) =&gt; (<br>   &lt;Route {...rest} render={props =&gt; (<br>       localStorage.getItem(&#39;auth&#39;) <br>       ? &lt;Component {...props} /&gt; <br>       : &lt;Redirect to={{ pathname: &#39;/&#39;, state: { from: props.location } }} /&gt;</pre><pre>   )} /&gt;<br>)</pre><p>In PrivateRoute.jsx file, we created a new component called PrivateRoute to check if auth has been set. We will be redirected to &#39;/&#39; if the auth is not set.</p><p>We will add the index.js file inside _components to export all components.</p><p>_components/index.js</p><pre>export * from &#39;./PrivateRoute&#39;;</pre><p>Now, we can access this PrivateRoute component and use it in our main routing in App.js. Also, we will create two components login and home. One each in public and private.</p><p>home/home.component.js</p><pre>import React, { Component } from &#39;react&#39;;<br>import PropTypes from &#39;prop-types&#39;;<br>import { withStyles } from &#39;@material-ui/core/styles&#39;;<br>import { connect } from &#39;react-redux&#39;;<br>import { withRouter } from &#39;react-router-dom&#39;;</pre><pre>const styles = theme =&gt; ({<br>     root: {<br>        flexGrow: 1,<br>     }<br>});</pre><pre><br>class Home extends Component {<br>     render() {<br>         const { classes } = this.props;<br>         return (<br>             &lt;div className={classes.root}&gt;<br>                &lt;h1&gt;Home&lt;/h1&gt;<br>             &lt;/div&gt;<br>         );<br>     }<br>}</pre><pre>Home.propTypes = {<br>    classes: PropTypes.object.isRequired<br>};</pre><pre><br>function mapStateToProps(state) {<br>    return state;<br>}</pre><pre><br>const connectedHomePage = withRouter(connect(mapStateToProps, null, null, {<br>     pure: false<br>})(withStyles(styles)(Home)));</pre><pre>export { connectedHomePage as Home };</pre><p>Here, we use proto-type for type-checking. As our application grows we can catch lots of bugs with type-checking. We are using connect function from react-redux to make sure it syncs up with the store and listen to each change happens in the state.</p><p>When there is a change in the state, it triggers the mapStateToProps function. In mapStateToProps function, we slice the state which is needed for this component. In this home component we are not yet started using any props, so we just return state.</p><p>home/index.js</p><pre>export * from &#39;./home.component&#39;;</pre><p>Now we can create our public route login</p><p>login/login.component.js</p><pre>import React, { Component } from &#39;react&#39;;<br>import PropTypes from &#39;prop-types&#39;;<br>import { withStyles } from &#39;@material-ui/core/styles&#39;;<br>import { connect } from &#39;react-redux&#39;;<br>import { withRouter } from &#39;react-router-dom&#39;;</pre><pre>const styles = theme =&gt; ({<br>    root: {<br>       flexGrow: 1,<br>    }<br>});</pre><pre>class Login extends Component {<br>     render() {<br>         const { classes } = this.props;<br>         return (<br>             &lt;div className={classes.root}&gt;<br>                &lt;h1&gt;Login&lt;/h1&gt;<br>             &lt;/div&gt;<br>         );<br>     }<br>}</pre><pre>Login.propTypes = {<br>     classes: PropTypes.object.isRequired<br>};</pre><pre>function mapStateToProps(state) {<br>     return state;<br>}</pre><pre>const connectedLoginPage = withRouter(connect(mapStateToProps, null, null, {<br>    pure: false<br>})(withStyles(styles)(Login)));</pre><pre>export { connectedLoginPage as Login };</pre><p>login/index.js</p><pre>export * from &#39;./login.component&#39;;</pre><p>As we have created both the routes needed. let’s modify the App.js</p><p>App.js</p><pre>import React, { Component } from &#39;react&#39;;<br>import &#39;./App.css&#39;;<br>import { Router, Switch, Route} from &#39;react-router-dom&#39;;<br>import  { Login } from &#39;./login/&#39;;<br>import { Home } from &#39;./home/&#39;;<br>import { history } from &#39;./_helpers&#39;;<br>import { PrivateRoute } from &#39;./_components&#39;;</pre><pre>class App extends Component {<br>    render() {<br>       return (<br>           &lt;div className=&quot;App&quot;&gt;<br>               &lt;Router history={history}&gt;<br>                 &lt;div&gt;<br>                     &lt;Switch&gt;<br>                        &lt;PrivateRoute exact path=&#39;/home&#39; component={Home} /&gt;<br>                        &lt;Route exact path=&#39;/&#39; component={Login} /&gt;<br>                     &lt;/Switch&gt;<br>                 &lt;/div&gt;<br>               &lt;/Router&gt;<br>           &lt;/div&gt;<br>        );<br>     }<br>}</pre><pre>export default App;</pre><p>As you have noticed we have imported Login, Home, and PrivateRoute we just created. You may also notice that we have also imported history from helpers to keep track of browser history. Since we may need it across our application we will be creating it as helpers.</p><p>_helpers/history.js</p><pre>import { createBrowserHistory } from &#39;history&#39;;</pre><pre>export const history = createBrowserHistory();</pre><p>_helpers/index.js</p><pre>export * from &#39;./history&#39;;</pre><p>Alright, since we have created all the files which are needed to run the basic app, we will now make the final modification to main index.js file to run our app. Also, since we are using redux to manage our state, its time to create redux store with reducer.</p><p>index.js</p><pre>import React from &#39;react&#39;;<br>import ReactDOM from &#39;react-dom&#39;;<br>import &#39;./index.css&#39;;<br>import App from &#39;./App&#39;;<br>import { createStore, applyMiddleware } from &#39;redux&#39;;<br>import { Provider } from &#39;react-redux&#39;;<br>import thunk from &#39;redux-thunk&#39;;<br>import reducer from &#39;./_reducers&#39;;<br>import registerServiceWorker from &#39;./registerServiceWorker&#39;;</pre><pre>const store = createStore(reducer, applyMiddleware(thunk))</pre><pre>ReactDOM.render(<br>    &lt;Provider store={store}&gt;<br>       &lt;App /&gt;<br>    &lt;/Provider&gt;<br>, document.getElementById(&#39;root&#39;));</pre><pre>registerServiceWorker();</pre><p>This leaves us with one more file to be created, which is our reducers. As we are not managing any states till now, we will just create an empty reducer. We will modify the reducers as we develop our application.</p><p>_reducers/index.js</p><pre>import { combineReducers } from &#39;redux&#39;;</pre><pre>const rootReducer = combineReducers({ });</pre><pre>export default rootReducer;</pre><p>We are all set to run our application.</p><pre>npm start</pre><p>This will run our react-redux application and we can see our login page with h1 tag. You can try and change the route in the browser to localhost:3000/home and you can see that you will be redirected to the login page. If so, then awesome, we are not redirected to home page because at this point of time we have not set the auth in localStorage.</p><p>the output looks like the following</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VZ7SZR29mnc5KlAMqWOXLQ.png" /></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FF9hQLAVhWnL56%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2FF9hQLAVhWnL56&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FF9hQLAVhWnL56%2F200.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="289" frameborder="0" scrolling="no"><a href="https://medium.com/media/3fc9ad623ce61364868911f41b871636/href">https://medium.com/media/3fc9ad623ce61364868911f41b871636/href</a></iframe><p>Great!!! Now we will add the actual login page and integrate the axios service to make the API call and get the response for the login and handle the response.</p><p>Note we will be using Material-UI for the component design, which I’m not going to discuss in detail over here. The <a href="https://material-ui.com/">official site</a> has a lot of examples to play around with.</p><p>Let’s modify our login page.</p><p>login/login.component.js</p><pre>import React, { Component } from &#39;react&#39;;<br>import PropTypes from &#39;prop-types&#39;;<br>import { withStyles } from &#39;@material-ui/core/styles&#39;;<br>import Paper from &#39;@material-ui/core/Paper&#39;;<br>import Grid from &#39;@material-ui/core/Grid&#39;;<br>import Button from &#39;@material-ui/core/Button&#39;;<br>import TextField from &#39;@material-ui/core/TextField&#39;;<br>import { connect } from &#39;react-redux&#39;;<br>import { userActions } from &#39;../_actions&#39;;<br>import { history } from &#39;../_helpers&#39;;<br>import Typography from &#39;@material-ui/core/Typography&#39;;<br>import { withRouter } from &#39;react-router-dom&#39;;<br>import &#39;./login.component.css&#39;</pre><pre>const styles = theme =&gt; ({<br>    root: {<br>       display: &#39;flex&#39;,<br>       flexWrap: &#39;wrap&#39;<br>    },</pre><pre>    container: {<br>       display: &#39;flex&#39;,<br>       flexWrap: &#39;wrap&#39;,<br>    },</pre><pre>    margin: {<br>       margin: theme.spacing.unit,<br>    },</pre><pre>    withoutLabel: {<br>       marginTop: theme.spacing.unit * 3,<br>    },</pre><pre>    textField: {<br>       marginLeft: theme.spacing.unit,<br>       marginRight: theme.spacing.unit,<br>       width: 200,<br>    },</pre><pre>    paper: {<br>       padding: theme.spacing.unit * 2,<br>       textAlign: &#39;center&#39;,<br>       color: theme.palette.text.secondary,<br>    },</pre><pre>    button: {<br>       margin: theme.spacing.unit,<br>    },</pre><pre>    input: {<br>       display: &#39;none&#39;,<br>    },<br>});</pre><pre><br>class Login extends Component {</pre><pre>     constructor(props){<br>         super(props);</pre><pre>         this.state = {<br>             username: &#39;&#39;,<br>             password: &#39;&#39;,<br>             showPassword: false,<br>         }<br>     }</pre><pre>     componentDidMount() {<br>         if(localStorage.getItem(&#39;auth&#39;)){<br>             history.push(&#39;/home&#39;);<br>         }<br>     }</pre><pre>     handleChange = prop =&gt; event =&gt; {<br>         this.setState({ [prop]: event.target.value });<br>     };</pre><pre>     login = event =&gt;{<br>         this.setState({ submitted: true });<br>         const { username, password } = this.state;<br>         const { dispatch } = this.props;<br>         if (username &amp;&amp; password) {<br>             dispatch(userActions.login(username, password));<br>         }<br>     }</pre><pre>     render() {<br>         const { classes } = this.props;<br>         return (<br>             &lt;div className=&quot;login-margin&quot;&gt;<br>                 &lt;Grid container spacing={24}&gt;<br>                    &lt;Grid item xs={3}&gt;<br>                    &lt;/Grid&gt;<br>                    &lt;Grid item xs={6}&gt;<br>                       &lt;Paper className={classes.paper}&gt;<br>                          &lt;Typography&gt;&lt;h1&gt;{&#39;Login&#39;}&lt;/h1&gt;&lt;/Typography<br>                       &lt;/Paper&gt;<br>                       &lt;Paper className={classes.paper}&gt;<br>                           &lt;div&gt;<br>                               &lt;TextField<br>                                label=&quot;Username&quot;<br>                                value={this.state.username}<br>                                className={classes.textField}<br>                                onChange = {this.handleChange(&#39;username&#39;)}<br>                               /&gt;<br>                               &lt;br/&gt;&lt;br/&gt;<br>                               &lt;TextField<br>                                label=&quot;Password&quot;<br>                                autoComplete=&quot;current-password&quot;<br>                                type={this.state.showPassword ? &#39;text&#39; : &#39;password&#39;}<br>                                className={classes.textField}<br>                                value={this.state.password}<br>                                onChange={this.handleChange(&#39;password&#39;)}<br>                              /&gt;<br>                              &lt;br/&gt;&lt;br/&gt;<br>                              &lt;Button variant=&quot;contained&quot; color=&quot;primary&quot; className={classes.button} onClick={(event)=&gt;{this.login()}}&gt;Login&lt;/Button&gt;<br>                          &lt;/div&gt;<br>                      &lt;/Paper&gt;<br>                 &lt;/Grid&gt;<br>                 &lt;Grid item xs={3}&gt;<br>                 &lt;/Grid&gt;<br>               &lt;/Grid&gt;<br>            &lt;/div&gt;<br>        );<br>    }<br>}</pre><pre>Login.propTypes = {<br>     classes: PropTypes.object.isRequired,<br>};</pre><pre><br>const mapStateToProps = (state) =&gt;{<br>     const { loggingIn } = state.authentication;<br>     return {<br>        loggingIn<br>     };<br>}</pre><pre>const connectedLoginPage = withRouter(connect(mapStateToProps, null, null, {<br>     pure: false<br>})(withStyles(styles)(Login)));</pre><pre>export { connectedLoginPage as Login };</pre><p>We will take a look at 3 functions and when and how they will react.</p><p>In componentDidMount function, we check the localStorage and do a redirect to the home page if the user is already logged in and the auth is set in localStorage.</p><p>In handleChange function, we set the State values of username and password. This function will be triggered on change of both username and password input textfield.</p><p>In login event handler we get the username and password from the state and use dispatch() to trigger the action.</p><p>We now need to create login action . Let’s group all our User related actions under userActions inside _actions</p><p>_actions/index.js</p><pre>export * from &#39;./user.actions&#39;;</pre><p>_actions/user.actions.js</p><pre>import { userService } from &#39;../_services/&#39;;<br>import { history } from &#39;../_helpers&#39;;</pre><pre>export const userActions = {<br>    login,<br>    logout<br>};</pre><pre>function login(username, password){<br>    return dispatch =&gt; {<br>       let apiEndpoint = &#39;auths&#39;;<br>       let payload = {<br>           username: username,<br>           password: password<br>       }</pre><pre>       userService.post(apiEndpoint, payload)<br>       .then((response)=&gt;{<br>           if (response.data.token) {<br>             localStorage.setItem(&#39;token&#39;, response.data.token);<br>             localStorage.setItem(&#39;auth&#39;, response.data.auth);<br>             dispatch(setUserDetails(response.data));<br>             history.push(&#39;/home&#39;);<br>           }<br>       })<br>    };<br>}</pre><pre>function logout(){<br>    return dispatch =&gt; {<br>        localStorage.removeItem(&#39;auth&#39;);<br>        localStorage.removeItem(&#39;token&#39;);<br>        dispatch(logoutUser());<br>        history.push(&#39;/&#39;);<br>    }<br>}</pre><pre>export function setUserDetails(user){<br>      return{<br>          type: &quot;LOGIN_SUCCESS&quot;,<br>          auth: user.auth,<br>          token: user.token<br>      }<br>}</pre><pre>export function logoutUser(){<br>      return{<br>          type: &quot;LOGOUT_SUCCESS&quot;,<br>          auth: false,<br>          token: &#39;&#39;<br>      }<br>}</pre><p>We have written two actions login and logout. You can notice that we have used userService.post() for handling post request. We will be passing endpoint for handling HTTP post method.</p><p>Before we add the service for the post request, we need to create reducers for getting state.authentication. Let’s do that.</p><p>_reducers/auth.reducer.js</p><pre>let token = localStorage.getItem(&#39;token&#39;);<br>let auth = localStorage.getItem(&#39;auth&#39;);</pre><pre><br>const initialState = auth ? { loggedIn: true, auth, token } : {};</pre><pre>export function authentication(state = initialState, action) {<br>    switch (action.type) {<br>        case &#39;LOGIN_SUCCESS&#39;:<br>            return {<br>                loggingIn: true,<br>                auth: action.auth,<br>                token: action.token<br>            };<br>      <br>        case &#39;LOGOUT_SUCCESS&#39;:<br>            return {<br>                auth: false<br>            };</pre><pre>        default:<br>            return state<br>    }<br>}</pre><p>_reducers/index.js</p><pre>import { combineReducers } from &#39;redux&#39;;<br>import { authentication } from &#39;./auth.reducer&#39;;</pre><pre><br>const rootReducer = combineReducers({<br>    authentication<br>});</pre><pre>export default rootReducer;</pre><p>Alright, we have created our first redux action and reducers.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fl0MYDGA3Du1hBR4xG%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fdeadpool-applause-clapping-l0MYDGA3Du1hBR4xG&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fl0MYDGA3Du1hBR4xG%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="226" frameborder="0" scrolling="no"><a href="https://medium.com/media/a986b7ce13241debae5ac2b8b62ec0a4/href">https://medium.com/media/a986b7ce13241debae5ac2b8b62ec0a4/href</a></iframe><p>We are now left with adding services</p><p>_services/user.service.js</p><pre>import axios from &#39;axios&#39;;<br>import config from &#39;../config/config&#39;;</pre><pre>export const userService = {<br>    get,<br>    post,<br>    put,<br>    deleteDetail<br>};</pre><pre>function get(apiEndpoint){<br>    return axios.get(config.baseUrl+apiEndpoint).then((response)=&gt;{<br>       return response;<br>    }).catch((err)=&gt;{<br>       console.log(err);<br>    })<br>}</pre><pre><br>function post(apiEndpoint, payload){<br>    return axios.post(config.baseUrl+apiEndpoint, payload).then((response)=&gt;{<br>        return response;<br>    }).catch((err)=&gt;{<br>        console.log(err);<br>    })<br>}</pre><pre>function put(apiEndpoint, payload){<br>    return axios.put(config.baseUrl+apiEndpoint, payload).then((response)=&gt;{<br>        return response;<br>    }).catch((err)=&gt;{<br>        console.log(err);<br>    })<br>}</pre><pre>function deleteDetail(apiEndpoint){<br>    return axios.delete(config.baseUrl+apiEndpoint).then((response)=&gt;{<br>        return response;<br>    }).catch((err)=&gt;{<br>        console.log(err);<br>    })<br>}</pre><p>We have written all 4 basic HTTP methods get, post, put, delete of axios to handle API calls as services.</p><p>_services/index.js</p><pre>export * from &#39;./user.service&#39;;</pre><p>Note, we have used confg.baseUrl to access the common base url. we will go ahead and add the config file.</p><p>config/config.js</p><pre>module.exports = {<br>    baseUrl: &#39;http://localhost:8001/api/v1/&#39;<br>}</pre><p>Now when we run our application, we can see the following screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xwurYKOzicTk7sZ6mAoupw.png" /></figure><p>Now let’s enter the username and password and test the app. If our username and password is valid, we will be redirected to home page and you can see the following output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ueH8foQeiz3Gn2byMGt_3g.png" /></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fl3fZGQvRA1cbqqcog%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Ffilmeditor--the-hangover-movie-l3fZGQvRA1cbqqcog&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fl3fZGQvRA1cbqqcog%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="183" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b87b643f0fd78dc8a481c07b69440db/href">https://medium.com/media/2b87b643f0fd78dc8a481c07b69440db/href</a></iframe><p>If you try to change the path in the browser to / it will redirect back to home page since we are checking is logged In or not.</p><p>Alright, we are now left with Adding vendor CRUD functionality. We will start by adding side navigation menu to switch between home page and vendor page. Also, we will handle logout in the side navigation menu.</p><p>_components/nav.js</p><pre>import React from &#39;react&#39;;<br>import PropTypes from &#39;prop-types&#39;;<br>import { withStyles } from &#39;@material-ui/core/styles&#39;;<br>import Drawer from &#39;@material-ui/core/Drawer&#39;;<br>import List from &#39;@material-ui/core/List&#39;;<br>import Divider from &#39;@material-ui/core/Divider&#39;;<br>import ListItem from &#39;@material-ui/core/ListItem&#39;;<br>import ListItemIcon from &#39;@material-ui/core/ListItemIcon&#39;;<br>import ListItemText from &#39;@material-ui/core/ListItemText&#39;;<br>import { userActions } from &#39;../_actions&#39;;<br>import { connect } from &#39;react-redux&#39;;<br>import HomeIcon from &#39;@material-ui/icons/Home&#39;;<br>import LogoutIcon from &#39;@material-ui/icons/HighlightOff&#39;;<br>import VendorIcon from &#39;@material-ui/icons/CardTravel&#39;;</pre><pre>const drawerWidth = 240;</pre><pre>const styles = theme =&gt; ({<br>    root: {<br>        flexGrow: 1,<br>    },</pre><pre>    appFrame: {<br>        zIndex: 1,<br>        overflow: &#39;hidden&#39;,<br>        position: &#39;relative&#39;,<br>        display: &#39;flex&#39;,<br>        width: &#39;100%&#39;,<br>    },</pre><pre>    appBar: {<br>        width: `calc(100% - ${drawerWidth}px)`,<br>    },</pre><pre>    &#39;appBar-left&#39;: {<br>         marginLeft: drawerWidth,<br>    },</pre><pre>    &#39;appBar-right&#39;: {<br>         marginRight: drawerWidth,<br>    },</pre><pre>    drawerPaper: {<br>        position: &#39;relative&#39;,<br>        width: drawerWidth,<br>    },</pre><pre>    toolbar: theme.mixins.toolbar,<br>        content: {<br>            flexGrow: 1,<br>            backgroundColor: theme.palette.background.default,<br>            padding: theme.spacing.unit * 3,<br>    },</pre><pre>});</pre><pre>class Navigation extends React.Component {<br>    constructor(props){<br>        super(props);<br>        this.state={<br>           anchor: &#39;left&#39;,<br>        }<br>    }</pre><pre>    logout = event =&gt;{<br>        const { dispatch } = this.props;<br>        dispatch(userActions.logout());<br>    }</pre><pre>    render() {<br>        const { classes } = this.props;<br>        const { anchor } = this.state;<br>        return(<br>            &lt;Drawer<br>             variant=&quot;permanent&quot;<br>             classes={{<br>                 paper: classes.drawerPaper,<br>             }}<br>             anchor={anchor}<br>            &gt;<br>               &lt;List component=&quot;nav&quot;&gt;<br>                  &lt;ListItem button component=&#39;a&#39; href=&quot;/home&quot;&gt;<br>                     &lt;ListItemIcon&gt;<br>                        &lt;HomeIcon /&gt;<br>                     &lt;/ListItemIcon&gt;<br>                     &lt;ListItemText primary=&quot;Home&quot;/&gt;<br>                  &lt;/ListItem&gt;<br>                  &lt;ListItem button component=&#39;a&#39; href=&quot;/vendor&quot;&gt;<br>                     &lt;ListItemIcon&gt;<br>                        &lt;VendorIcon /&gt;<br>                     &lt;/ListItemIcon&gt;<br>                     &lt;ListItemText primary=&quot;Vendors&quot;/&gt;<br>                  &lt;/ListItem&gt;<br>                  &lt;ListItem button onClick={(event)=&gt;{this.logout()}}&gt;<br>                     &lt;ListItemIcon&gt;<br>                        &lt;LogoutIcon /&gt;<br>                     &lt;/ListItemIcon&gt;<br>                     &lt;ListItemText primary=&quot;Logout&quot;/&gt;<br>                  &lt;/ListItem&gt;<br>               &lt;/List&gt;<br>               &lt;Divider /&gt;<br>           &lt;/Drawer&gt;<br>        );<br>    }<br>}</pre><pre>Navigation.propTypes = {<br>    classes: PropTypes.object.isRequired,<br>};</pre><pre>const mapStateToProps = (state) =&gt;{<br>    const { loggingIn } = state.authentication;<br>    return {<br>       loggingIn<br>    };<br>}</pre><pre>export default connect(mapStateToProps)(withStyles(styles)(Navigation));</pre><p>Along with the side navigation menu, we are handling logout functionality as well.</p><p>_components/appbar.js</p><pre>import React from &#39;react&#39;;<br>import PropTypes from &#39;prop-types&#39;;<br>import classNames from &#39;classnames&#39;;<br>import { withStyles } from &#39;@material-ui/core/styles&#39;;<br>import AppBar from &#39;@material-ui/core/AppBar&#39;;<br>import Toolbar from &#39;@material-ui/core/Toolbar&#39;;<br>import Typography from &#39;@material-ui/core/Typography&#39;;</pre><pre>const drawerWidth = 240;</pre><pre>const styles = theme =&gt; ({<br>    root: {<br>        flexGrow: 1,<br>    },</pre><pre>    appFrame: {<br>        zIndex: 1,<br>        overflow: &#39;hidden&#39;,<br>        position: &#39;relative&#39;,<br>        display: &#39;flex&#39;,<br>        width: &#39;100%&#39;,<br>    },</pre><pre>    appBar: {<br>        width: `calc(100% - ${drawerWidth}px)`,<br>    },</pre><pre>    &#39;appBar-left&#39;: {<br>        marginLeft: drawerWidth,<br>    },</pre><pre>    &#39;appBar-right&#39;: {<br>        marginRight: drawerWidth,<br>    },</pre><pre>    drawerPaper: {<br>        position: &#39;relative&#39;,<br>        width: drawerWidth,<br>    },</pre><pre>    toolbar: theme.mixins.toolbar,<br>    <br>    content: {<br>        flexGrow: 1,<br>        backgroundColor: theme.palette.background.default,<br>        padding: theme.spacing.unit * 3,<br>    },</pre><pre>});</pre><pre>class PermanentDrawer extends React.Component {<br>    state = {<br>       anchor: &#39;left&#39;,<br>    };</pre><pre>    handleChange = event =&gt; {<br>        this.setState({<br>            anchor: event.target.value,<br>        });<br>    };</pre><pre>    render() {<br>        const { classes } = this.props;<br>        const { anchor } = this.state;</pre><pre>        return (<br>            &lt;AppBar<br>             position=&quot;absolute&quot;<br>             className={classNames(classes.appBar, classes[`appBar-${anchor}`])}<br>            &gt;<br>               &lt;Toolbar&gt;<br>                  &lt;Typography variant=&quot;title&quot; color=&quot;inherit&quot; noWrap&gt;<br>                   CRUD<br>                  &lt;/Typography&gt;<br>                &lt;/Toolbar&gt;<br>           &lt;/AppBar&gt;<br>        );<br>    }<br>}</pre><pre>PermanentDrawer.propTypes = {<br>    classes: PropTypes.object.isRequired,<br>};</pre><pre>export default withStyles(styles)(PermanentDrawer);</pre><p>Now let’s include the navigation drawer in the home page. The modified home page looks like the following.</p><p>home/home.component.js</p><pre>import React, { Component } from &#39;react&#39;;<br>import PropTypes from &#39;prop-types&#39;;<br>import { withStyles } from &#39;@material-ui/core/styles&#39;;<br>import { connect } from &#39;react-redux&#39;;<br>import { withRouter } from &#39;react-router-dom&#39;;<br>import Typography from &#39;@material-ui/core/Typography&#39;;<br>import AppBar from &#39;../_components/appbar&#39;;<br>import Nav from &#39;../_components/nav&#39;;</pre><pre>const drawerWidth = 240;</pre><pre>const styles = theme =&gt; ({<br>    root: {<br>        flexGrow: 1,<br>    },</pre><pre>    appFrame: {<br>        zIndex: 1,<br>        overflow: &#39;hidden&#39;,<br>        position: &#39;relative&#39;,<br>        display: &#39;flex&#39;,<br>        width: &#39;100%&#39;,<br>    },</pre><pre>    appBar: {<br>        width: `calc(100% - ${drawerWidth}px)`,<br>    },</pre><pre>    &#39;appBar-left&#39;: {<br>        marginLeft: drawerWidth,<br>    },</pre><pre>    &#39;appBar-right&#39;: {<br>        marginRight: drawerWidth,<br>    },</pre><pre>    drawerPaper: {<br>        position: &#39;relative&#39;,<br>        width: drawerWidth,<br>    },</pre><pre>    toolbar: theme.mixins.toolbar,<br>    content: {<br>        flexGrow: 1,<br>        backgroundColor: theme.palette.background.default,<br>        padding: theme.spacing.unit * 3,<br>    },<br>});</pre><pre>class Home extends Component {<br>    render() {<br>        const { classes } = this.props;<br>        return (<br>            &lt;div className={classes.root}&gt;<br>               &lt;div className={classes.appFrame}&gt;<br>                 &lt;AppBar/&gt;<br>                 &lt;Nav /&gt;<br>                 &lt;main className={classes.content}&gt;<br>                     &lt;div className={classes.toolbar} /&gt;<br>                     &lt;Typography&gt;{&#39;Home&#39;}&lt;/Typography&gt;<br>                 &lt;/main&gt;<br>               &lt;/div&gt;<br>            &lt;/div&gt;<br>        );<br>    }<br>}</pre><pre>Home.propTypes = {<br>    classes: PropTypes.object.isRequired,<br>};</pre><pre><br>function mapStateToProps(state) {<br>    return state;<br>}</pre><pre>const connectedHomePage = withRouter(connect(mapStateToProps, null, null, {<br>    pure: false<br>})(withStyles(styles)(Home)));</pre><pre>export { connectedHomePage as Home };</pre><p>Note that we have included the two component appbar and nav.</p><p>Now the home page looks like the following.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Eecxmn066W5S-STVqEowsA.png" /></figure><p>Moving ahead we will add &#39;/vendor’ path and component in the routing as private routing for the listing of vendors. We need to add the following lines in App.js</p><p>App.js</p><pre>...<br>import Vendor from &#39;./vendors/vendor.component&#39;;<br>...</pre><pre>&lt;Switch&gt;<br>    &lt;PrivateRoute exact path=&#39;/home&#39; component={Home} /<br>    &lt;PrivateRoute exact path=&#39;/vendor&#39; component={Vendor} /&gt;<br>    &lt;Route exact path=&#39;/&#39; component={Login} /&gt;<br>&lt;/Switch&gt;</pre><p>The App.js file looks like the following.</p><p>App.js</p><pre>import React, { Component } from &#39;react&#39;;<br>import &#39;./App.css&#39;;<br>import { Router, Switch, Route} from &#39;react-router-dom&#39;;<br>import { Vendor } from &#39;./vendors/vendor.component&#39;;<br>import  { Login } from &#39;./login/&#39;;<br>import { Home } from &#39;./home/&#39;;<br>import { history } from &#39;./_helpers&#39;;<br>import { PrivateRoute } from &#39;./_components&#39;;</pre><pre>class App extends Component {<br>    render() {<br>        return (<br>            &lt;div className=&quot;App&quot;&gt;<br>                &lt;Router history={history}&gt;<br>                   &lt;div&gt;<br>                      &lt;Switch&gt;<br>                         &lt;PrivateRoute exact path=&#39;/home&#39; component={Home} /&gt;<br>                         &lt;PrivateRoute exact path=&#39;/vendor&#39; component={Vendor} /&gt;<br>                         &lt;Route exact path=&#39;/&#39; component={Login} /&gt;<br>                      &lt;/Switch&gt;<br>                   &lt;/div&gt;<br>                &lt;/Router&gt;<br>            &lt;/div&gt;<br>        );<br>    }</pre><pre>}</pre><pre>export default App;</pre><p>We have imported Vendor component but we are yet to create one. so let’s go ahead and create it.</p><p>vendors/vendor.component.js</p><pre>import { connect } from &#39;react-redux&#39;;<br>import { vendorAction } from &#39;../_actions&#39;;<br>import React, { Component } from &#39;react&#39;;<br>import AppBar from &#39;../_components/appbar&#39;;<br>import PropTypes from &#39;prop-types&#39;;<br>import { withStyles } from &#39;@material-ui/core/styles&#39;;<br>import Typography from &#39;@material-ui/core/Typography&#39;;<br>import Nav from &#39;../_components/nav&#39;;<br>import Table from &#39;@material-ui/core/Table&#39;;<br>import TableBody from &#39;@material-ui/core/TableBody&#39;;<br>import TableCell from &#39;@material-ui/core/TableCell&#39;;<br>import TableHead from &#39;@material-ui/core/TableHead&#39;;<br>import TableRow from &#39;@material-ui/core/TableRow&#39;;<br>import Paper from &#39;@material-ui/core/Paper&#39;;<br>import Grid from &#39;@material-ui/core/Grid&#39;;<br>import Button from &#39;@material-ui/core/Button&#39;;<br>import DeleteIcon from &#39;@material-ui/icons/Delete&#39;;<br>import EditIcon from &#39;@material-ui/icons/Edit&#39;;<br>import IconButton from &#39;@material-ui/core/IconButton&#39;;<br>import { withRouter } from &#39;react-router-dom&#39;;</pre><pre>const drawerWidth = 240;</pre><pre>const styles = theme =&gt; ({<br>    root: {<br>        flexGrow: 1,<br>    },</pre><pre>    appFrame: {<br>       zIndex: 1,<br>       overflow: &#39;hidden&#39;,<br>       position: &#39;relative&#39;,<br>       display: &#39;flex&#39;,<br>       width: &#39;100%&#39;,<br>    },</pre><pre>    appBar: {<br>       width: `calc(100% - ${drawerWidth}px)`,<br>    },</pre><pre>    &#39;appBar-left&#39;: {<br>        marginLeft: drawerWidth,<br>    },</pre><pre>    &#39;appBar-right&#39;: {<br>        marginRight: drawerWidth,<br>    },</pre><pre>    drawerPaper: {<br>        position: &#39;relative&#39;,<br>        width: drawerWidth,<br>    },</pre><pre>    toolbar: theme.mixins.toolbar,<br>    content: {<br>        flexGrow: 1,<br>        backgroundColor: theme.palette.background.default,<br>        padding: theme.spacing.unit * 3,<br>    },</pre><pre>    paper: {<br>        position: &#39;absolute&#39;,<br>        width: theme.spacing.unit * 50,<br>        backgroundColor: theme.palette.background.paper,<br>        boxShadow: theme.shadows[5],<br>        padding: theme.spacing.unit * 4,<br>    },<br>});</pre><pre>class Vendor extends Component {<br>    componentDidMount() {<br>        const { dispatch } = this.props;<br>        dispatch(vendorAction.getVendor());<br>    }</pre><pre>    handleChange = event =&gt; {<br>        this.setState({<br>            anchor: event.target.value,<br>        });<br>    };</pre><pre>    handleClick = (event, id) =&gt; {<br>        const { dispatch } = this.props;<br>        dispatch(vendorAction.deleteVendorById(id))<br>    };</pre><pre>    render() {<br>        const { classes } = this.props;<br>        const { vendor } = this.props.vendor;<br>        return (<br>            &lt;div className={classes.root}&gt;<br>              &lt;div className={classes.appFrame}&gt;<br>                &lt;AppBar/&gt;<br>                &lt;Nav /&gt;<br>                &lt;main className={classes.content}&gt;<br>                   &lt;div className={classes.toolbar} /&gt;<br>                   &lt;Grid container spacing={24}&gt;<br>                      &lt;Grid item xs={3}&gt;<br>                         &lt;Typography&gt;{&#39;Vendor&#39;}&lt;/Typography&gt;<br>                      &lt;/Grid&gt;<br>                      &lt;Grid item xs={6}&gt;<br>                      &lt;/Grid&gt;<br>                      &lt;Grid item xs={3} container justify=&quot;flex-end&quot;&gt;<br>                      &lt;/Grid&gt;<br>                   &lt;/Grid&gt;<br>                   &lt;Grid container spacing={24}&gt;<br>                      &lt;Grid item xs={3}&gt;<br>                      &lt;/Grid&gt;<br>                      &lt;Grid item xs={6}&gt;<br>                      &lt;/Grid&gt;<br>                      &lt;Grid item xs={3} container justify=&quot;flex-end&quot;&gt;<br>                          &lt;Button variant=&quot;contained&quot; color=&quot;primary&quot; className={classes.button} component=&#39;a&#39; href=&quot;/add-vendor&quot;&gt;Add Vendor&lt;/Button&gt;</pre><pre>                      &lt;/Grid&gt;</pre><pre>                   &lt;/Grid&gt;<br>                   &lt;br /&gt;&lt;br /&gt;<br>                   &lt;Grid container spacing={24}&gt;<br>                     &lt;Paper className={classes.root}&gt;<br>                       &lt;Table className={classes.table}&gt;<br>                          &lt;TableHead&gt;<br>                             &lt;TableRow&gt;<br>                                &lt;TableCell&gt;Name&lt;/TableCell&gt;<br>                                &lt;TableCell numeric&gt;Mobile&lt;/TableCell&gt;<br>                                &lt;TableCell numeric&gt;Phone&lt;/TableCell&gt;<br>                                &lt;TableCell&gt;Address&lt;/TableCell&gt;<br>                                &lt;TableCell&gt;Action&lt;/TableCell&gt;<br>                             &lt;/TableRow&gt;<br>                          &lt;/TableHead&gt;<br>                          &lt;TableBody&gt;<br>                           {vendor.map(n =&gt; {<br>                              return (<br>                                  &lt;TableRow key={n._id}&gt;<br>                                    &lt;TableCell component=&quot;th&quot; scope=&quot;row&quot;&gt;<br>                                      {n.name}<br>                                    &lt;/TableCell&gt;<br>                                    &lt;TableCell numeric&gt;{n.mobile}&lt;/TableCell&gt;<br>                                    &lt;TableCell numeric&gt;{n.phone_number}&lt;/TableCell&gt;<br>                                    &lt;TableCell&gt;{n.address}&lt;/TableCell&gt;<br>                                    &lt;TableCell&gt;<br>                                        &lt;IconButton className={classes.button} aria-label=&quot;Edit&quot; component=&#39;a&#39; href={`/edit-vendor/${n._id}`}&gt;<br>                                           &lt;EditIcon /&gt;<br>                                        &lt;/IconButton&gt;<br>                                        &lt;IconButton className={classes.button} aria-label=&quot;Delete&quot; onClick={(event) =&gt; this.handleClick(event, n._id)}&gt;<br>                                           &lt;DeleteIcon /&gt; <br>                                        &lt;/IconButton&gt;<br>                                    &lt;/TableCell&gt;<br>                                 &lt;/TableRow&gt;<br>                             );<br>                           })}<br>                        &lt;/TableBody&gt;<br>                     &lt;/Table&gt;<br>                  &lt;/Paper&gt;<br>              &lt;/Grid&gt;<br>           &lt;/main&gt;<br>       &lt;/div&gt;<br>     &lt;/div&gt;<br>   );<br>  }</pre><pre>}</pre><pre>Vendor.propTypes = {<br>     classes: PropTypes.object.isRequired,<br>};</pre><pre>const mapStateToProps = (state) =&gt;{<br>    return {<br>       vendor : state.vendor<br>    };<br>}</pre><pre>const connectedVendorPage = withRouter(connect(mapStateToProps, null, null, {<br>    pure: false<br>})(withStyles(styles)(Vendor)));</pre><pre>export { connectedVendorPage as Vendor };</pre><p>Note we have already written onclick function to handle delete button click. All we need to add is its respective action in vendor.action , which we will add later.</p><p>Now we need to add vendorAction.</p><p>_actions/vendor.actions.js</p><pre>import { userService } from &#39;../_services/&#39;;<br>import { history } from &#39;../_helpers&#39;;</pre><pre>export const vendorAction = {<br>    getVendor<br>};</pre><pre>function getVendor(){<br>    return dispatch =&gt; {<br>        let apiEndpoint = &#39;vendors&#39;;<br>        userService.get(apiEndpoint)<br>        .then((response)=&gt;{<br>            dispatch(changeVendorsList(response.data.data));<br>        }).catch((err)=&gt;{<br>            console.log(err);<br>        })<br>    };<br>}</pre><pre>export function changeVendorsList(vendor){<br>    return{<br>        type: &quot;FETECHED_ALL_VENDOR&quot;,<br>        vendor: vendor<br>    }<br>}</pre><p>Now we need to export the vendor.action from the _actions/index.js file.</p><p>_actions/index.js</p><pre>export * from &#39;./user.actions&#39;;<br>export * from &#39;./vendor.actions&#39;</pre><p>Great!! Let’s add the vendor.reducer.js</p><p>_reducers/vendor.reducer.js</p><pre>const initialState = { <br>    anchor: &#39;left&#39;,<br>    vendor: [],<br>    open: false,<br>    id: &#39;&#39;,<br>    name: &#39;&#39;,<br>    mobile: &#39;&#39;,<br>    phone_number: &#39;&#39;,<br>    address: &#39;&#39;<br>};</pre><pre>export function vendor(state = initialState, action) {<br>    switch (action.type) {<br>        case &#39;FETECHED_ALL_VENDOR&#39;:<br>            return {<br>                ...state,<br>                vendor: action.vendor<br>            };<br>        default:<br>            return state<br>     }<br>}</pre><p>_reducers/index.js</p><pre>import { combineReducers } from &#39;redux&#39;;<br>import { authentication } from &#39;./auth.reducer&#39;;<br>import { vendor } from &#39;./vendor.reducer&#39;;</pre><pre>const rootReducer = combineReducers({<br>    authentication,<br>    vendor<br>});</pre><pre>export default rootReducer;</pre><p>Now when we run the app we will get 403 error.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FSid4QgwDxJ8l2%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fbatman-reaction-Sid4QgwDxJ8l2&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FSid4QgwDxJ8l2%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="326" frameborder="0" scrolling="no"><a href="https://medium.com/media/6346f65f32b64f06921b22ed293aff5e/href">https://medium.com/media/6346f65f32b64f06921b22ed293aff5e/href</a></iframe><p>Remember we need to send token for all our API calls after login. So let’s modify the user.service.js to send token in hearders</p><pre>import axios from &#39;axios&#39;;<br>import config from &#39;../config/config&#39;;</pre><pre><br>export const userService = {<br>    get,<br>    post,<br>    put,<br>    deleteDetail<br>};</pre><pre>function get(apiEndpoint){<br>    return axios.get(config.baseUrl+apiEndpoint, getOptions())<br>    .then((response)=&gt;{<br>        return response;<br>    }).catch((err)=&gt;{<br>        console.log(err);<br>    })<br>}</pre><pre>function post(apiEndpoint, payload){<br>    return axios.post(config.baseUrl+apiEndpoint, payload, getOptions())<br>    .then((response)=&gt;{<br>        return response;<br>    }).catch((err)=&gt;{<br>        console.log(err);<br>    })<br>}</pre><pre>function put(apiEndpoint, payload){<br>    return axios.put(config.baseUrl+apiEndpoint, payload, getOptions())<br>    .then((response)=&gt;{<br>        return response;<br>    }).catch((err)=&gt;{<br>        console.log(err);<br>    })<br>}</pre><pre>function deleteDetail(apiEndpoint){<br>    return axios.delete(config.baseUrl+apiEndpoint, getOptions())<br>    .then((response)=&gt;{<br>        return response;<br>    }).catch((err)=&gt;{<br>        console.log(err);<br>    })<br>}</pre><pre>function getOptions(){<br>    let options = {};<br>    if(localStorage.getItem(&#39;token&#39;)){<br>        options.headers = { &#39;x-access-token&#39;: localStorage.getItem(&#39;token&#39;) };<br>    }<br>    return options;<br>}</pre><p>When we run the application we can get the vendor details and display it in table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2z7xwknqdEK-ccSoweHcOg.png" /></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FEU42nA5hrKn16%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fthe-mask-EU42nA5hrKn16&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FEU42nA5hrKn16%2F200.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="284" frameborder="0" scrolling="no"><a href="https://medium.com/media/15e93ce6f702c81af0da44b9b7efc9cf/href">https://medium.com/media/15e93ce6f702c81af0da44b9b7efc9cf/href</a></iframe><p>Now let’s add script for Add Vendor ,Edit Vendor and Delete Vendor .</p><p>App.js</p><pre>...<br>import { AddVendor } from &#39;./vendors/addvendor.component&#39;<br>...<br>&lt;PrivateRoute exact path=&#39;/add-vendor&#39; component={AddVendor} /&gt;&lt;PrivateRoute exact path=&#39;/edit-vendor/:id&#39; component={AddVendor} /&gt;<br>...</pre><p>Since add and edit has the same fields, we are going to reuse the same form. Let’s create addvendor.component and handle add and edit.</p><p>vendors/addvendor.component.js</p><pre>import React, { Component } from &#39;react&#39;;<br>import AppBar from &#39;../_components/appbar&#39;;<br>import PropTypes from &#39;prop-types&#39;;<br>import { withStyles } from &#39;@material-ui/core/styles&#39;;<br>import Typography from &#39;@material-ui/core/Typography&#39;;<br>import Nav from &#39;../_components/nav&#39;;<br>import Paper from &#39;@material-ui/core/Paper&#39;;<br>import Grid from &#39;@material-ui/core/Grid&#39;;<br>import Button from &#39;@material-ui/core/Button&#39;;<br>import TextField from &#39;@material-ui/core/TextField&#39;;<br>import { connect } from &#39;react-redux&#39;;<br>import { vendorAction } from &#39;../_actions&#39;;<br>import { withRouter } from &#39;react-router-dom&#39;;</pre><pre>const drawerWidth = 240;</pre><pre>const styles = theme =&gt; ({<br>    root: {<br>        flexGrow: 1,<br>    },</pre><pre>    contentRoot: {<br>        ...theme.mixins.gutters(),<br>        paddingTop: theme.spacing.unit * 2,<br>        paddingBottom: theme.spacing.unit * 2,<br>    },</pre><pre>    appFrame: {<br>        zIndex: 1,<br>        overflow: &#39;hidden&#39;,<br>        position: &#39;relative&#39;,<br>        display: &#39;flex&#39;,<br>        width: &#39;100%&#39;,<br>    },</pre><pre>    appBar: {<br>        width: `calc(100% - ${drawerWidth}px)`,<br>    },</pre><pre>    &#39;appBar-left&#39;: {<br>        marginLeft: drawerWidth,<br>    },</pre><pre>    &#39;appBar-right&#39;: {<br>        marginRight: drawerWidth,<br>    },</pre><pre>    drawerPaper: {<br>        position: &#39;relative&#39;,<br>        width: drawerWidth,<br>    },</pre><pre>    toolbar: theme.mixins.toolbar,</pre><pre>    content: {<br>        flexGrow: 1,<br>        backgroundColor: theme.palette.background.default,<br>        padding: theme.spacing.unit * 3,<br>    },<br>});</pre><pre>class AddVendor extends Component {<br>    handleChange = prop =&gt; event =&gt; {<br>        const { dispatch } = this.props;<br>        dispatch(vendorAction.onChangeProps(prop, event));<br>    };</pre><pre>    componentDidMount() {<br>        const { match : { params } } = this.props;<br>        if(params.id){<br>            const { dispatch } = this.props;<br>            dispatch(vendorAction.getVendorById(params.id));<br>        }<br>    }</pre><pre>    handleClick(event){<br>        const { match : { params } } = this.props;<br>        const { dispatch } = this.props;<br>        let payload={<br>            name: this.props.vendor.name,<br>            mobile: this.props.vendor.mobile,<br>            phone_number: this.props.vendor.phone_number,<br>            address: this.props.vendor.address,<br>        }</pre><pre>        if(params.id){<br>            dispatch(vendorAction.editVendorInfo(params.id, payload));<br>        }else{<br>            dispatch(vendorAction.createVendor(payload));<br>        }<br>    }</pre><pre>    render() {<br>        const { classes } = this.props;<br>        const { match : { params } } = this.props;</pre><pre>        function InsertText(props) {<br>            return &lt;Typography&gt;{&#39;Add New Vendor&#39;}&lt;/Typography&gt;;<br>        }</pre><pre><br>        function EditText(props) {<br>            return &lt;Typography&gt;{&#39;Edit Vendor&#39;}&lt;/Typography&gt;;<br>        }</pre><pre>        function SegHeader() {<br>            if(params.id){<br>                return &lt;EditText /&gt;;<br>            }<br>            return &lt;InsertText /&gt;;<br>        }</pre><pre>        return (<br>            &lt;div className={classes.root}&gt;<br>               &lt;div className={classes.appFrame}&gt;<br>                  &lt;AppBar/&gt;<br>                  &lt;Nav /&gt;<br>                  &lt;main className={classes.content}&gt;<br>                      &lt;div className={classes.toolbar} /&gt;<br>                      &lt;Grid container spacing={24}&gt;<br>                         &lt;Grid item xs={3}&gt;<br>                            &lt;SegHeader /&gt;<br>                         &lt;/Grid&gt;<br>                         &lt;Grid item xs={6}&gt;<br>                         &lt;/Grid&gt;<br>                         &lt;Grid item xs={3} container justify=&quot;flex-end&quot;&gt;<br>                         &lt;/Grid&gt;<br>                     &lt;/Grid&gt;<br>                     &lt;br /&gt;&lt;br /&gt;<br>                     &lt;Grid container spacing={24}&gt;<br>                        &lt;Grid item xs={12}&gt;<br>                        &lt;div&gt;<br>                          &lt;Paper className={classes.contentRoot} elevation={1}&gt;<br>                             &lt;form className={classes.container}&gt;<br>                                &lt;Grid container spacing={24}&gt;<br>                                   &lt;Grid item xs={3}&gt;<br>                                      &lt;TextField<br>                                       id=&quot;name&quot;<br>                                       label=&quot;Name&quot;<br>                                       className={classes.textField}<br>                                       value={this.props.vendor.name}<br>                                       onChange={this.handleChange(&#39;name&#39;)}<br>                                       margin=&quot;normal&quot;<br>                                      /&gt;<br>                                   &lt;/Grid&gt;<br>                                   &lt;Grid item xs={3}&gt;<br>                                      &lt;TextField<br>                                       id=&quot;mobile&quot;<br>                                       label=&quot;Mobile&quot;<br>                                       className={classes.textField}<br>                                       value={this.props.vendor.mobile}<br>                                       onChange={this.handleChange(&#39;mobile&#39;)}<br>                                       margin=&quot;normal&quot;<br>                                      /&gt;<br>                                   &lt;/Grid&gt;<br>                                   &lt;Grid item xs={3}&gt;<br>                                      &lt;TextField<br>                                       id=&quot;phone_number&quot;<br>                                       label=&quot;Phone&quot;<br>                                       className={classes.textField}<br>                                       value={this.props.vendor.phone_number}<br>                                       onChange={this.handleChange(&#39;phone_number&#39;)}<br>                                       margin=&quot;normal&quot;<br>                                      /&gt;<br>                                   &lt;/Grid&gt;<br>                                   &lt;Grid item xs={3}&gt;<br>                                      &lt;TextField<br>                                       id=&quot;address&quot;<br>                                       label=&quot;Address&quot;<br>                                       multiline<br>                                       rowsMax=&quot;4&quot;<br>                                       className={classes.textField}<br>                                       value={this.props.vendor.address}<br>                                       onChange={this.handleChange(&#39;address&#39;)}<br>                                       margin=&quot;normal&quot;<br>                                      /&gt;<br>                                   &lt;/Grid&gt;<br>                                &lt;/Grid&gt;<br>                                &lt;br /&gt;<br>                                &lt;Grid container spacing={24}&gt;<br>                                   &lt;Grid item xs={3}&gt;<br>                                   &lt;/Grid&gt;<br>                                   &lt;Grid item xs={6}&gt;<br>                                   &lt;/Grid&gt;<br>                                   &lt;Grid item xs={3} container justify=&quot;center&quot;&gt;<br>                                      &lt;Grid container spacing={24}&gt;<br>                                         &lt;Grid item xs={6} container justify=&quot;center&quot;&gt;<br>                                            &lt;Button variant=&quot;contained&quot; color=&quot;secondary&quot; className={classes.button} component=&#39;a&#39; href=&quot;/vendor&quot;&gt;Cancel&lt;/Button&gt;<br>                                         &lt;/Grid&gt;<br>                                         &lt;Grid item xs={6} container justify=&quot;flex-start&quot;&gt;<br>                                            &lt;Button variant=&quot;contained&quot; color=&quot;primary&quot; className={classes.button} onClick={(event) =&gt; this.handleClick(event)}&gt;Save&lt;/Button&gt;<br>                                         &lt;/Grid&gt;<br>                                      &lt;/Grid&gt;<br>                                   &lt;/Grid&gt;<br>                                &lt;/Grid&gt;<br>                             &lt;/form&gt;<br>                           &lt;/Paper&gt;<br>                         &lt;/div&gt;<br>                       &lt;/Grid&gt;<br>                     &lt;/Grid&gt;<br>                  &lt;/main&gt;<br>                &lt;/div&gt;<br>              &lt;/div&gt;<br>        );<br>    }<br>}</pre><pre>AddVendor.propTypes = {<br>    classes: PropTypes.object.isRequired,<br>};</pre><pre>const mapStateToProps = (state) =&gt;{<br>    return state;<br>}</pre><pre><br>const connectedAddVendorPage = withRouter(connect(mapStateToProps, null, null, {<br>    pure: false<br>})(withStyles(styles)(AddVendor)));</pre><pre>export { connectedAddVendorPage as AddVendor };</pre><p>handleChange event handler function triggers onChangeProps action to update the state on the change in form input so that the state holds the updated value all the time. Also it only passes the props which currently changes.</p><p>componentDidMount check for URL params, if the params have an id, then the form is opened in edit mode, so it triggers getVendorById action method to get the vendor details for editing.</p><p>handleClick method handles both create new and update vendor with createVendor and editVendorInfo respectively.</p><p>_actions/vendor.action.js</p><pre>import { userService } from &#39;../_services/&#39;;<br>import { history } from &#39;../_helpers&#39;;</pre><pre><br>export const vendorAction = {<br>    getVendor,<br>    getVendorById,<br>    onChangeProps,<br>    editVendorInfo,<br>    createVendor,<br>    deleteVendorById<br>};</pre><pre>function getVendor(){<br>    return dispatch =&gt; {<br>        let apiEndpoint = &#39;vendors&#39;;<br>        userService.get(apiEndpoint)<br>        .then((response)=&gt;{<br>            dispatch(changeVendorsList(response.data.data));<br>        }).catch((err)=&gt;{<br>            console.log(err);<br>        })<br>   };<br>}</pre><pre>function createVendor(payload){<br>    return dispatch =&gt; {<br>        let apiEndpoint = &#39;vendors/&#39;;<br>        userService.post(apiEndpoint, payload)<br>        .then((response)=&gt;{<br>            dispatch(createUserInfo());<br>            history.push(&#39;/vendor&#39;);<br>        })<br>    }<br>}</pre><pre>function getVendorById(id){<br>    return dispatch =&gt; {<br>        let apiEndpoint = &#39;vendors/&#39;+ id;<br>        userService.get(apiEndpoint)<br>        .then((response)=&gt;{<br>            dispatch(editVendorsDetails(response.data.data));<br>        })<br>    };<br>}</pre><pre>function onChangeProps(props, event){<br>    return dispatch =&gt;{<br>        dispatch(handleOnChangeProps(props, event.target.value));<br>    }<br>}</pre><pre>function editVendorInfo(id, payload){<br>    return dispatch =&gt; {<br>        let apiEndpoint = &#39;vendors/&#39;+ id;<br>        userService.put(apiEndpoint, payload)<br>        .then((response)=&gt;{<br>            dispatch(updatedUserInfo());<br>            history.push(&#39;/vendor&#39;);<br>        })<br>    }<br>}</pre><pre>function deleteVendorById(id){<br>    return dispatch =&gt; {<br>        let apiEndpoint = &#39;vendors/&#39;+ id;<br>        userService.deleteDetail(apiEndpoint)<br>        .then((response)=&gt;{<br>             dispatch(deleteVendorsDetails());<br>             dispatch(vendorAction.getVendor());<br>        })<br>    };<br>}</pre><pre>export function changeVendorsList(vendor){<br>    return{<br>        type: &quot;FETECHED_ALL_VENDOR&quot;,<br>        vendor: vendor<br>    }<br>}</pre><pre>export function handleOnChangeProps(props, value){<br>    return{<br>        type: &quot;HANDLE_ON_CHANGE&quot;,<br>        props: props,<br>        value: value<br>    }<br>}</pre><pre>export function editVendorsDetails(vendor){<br>    return{<br>        type: &quot;VENDOR_DETAIL&quot;,<br>        id: vendor._id,<br>        name: vendor.name,<br>        mobile: vendor.mobile,<br>        phone_number: vendor.phone_number,<br>        address: vendor.address<br>    }<br>}</pre><pre>export function updatedUserInfo(){<br>    return{<br>        type: &quot;USER_UPDATED&quot;<br>    }<br>}</pre><pre>export function createUserInfo(){<br>    return{<br>        type: &quot;USER_CREATED_SUCCESSFULLY&quot;<br>    }<br>}</pre><pre>export function deleteVendorsDetails(){<br>    return{<br>        type: &quot;DELETED_VENDOR_DETAILS&quot;<br>    }<br>}</pre><p>Now, all we left with is to modify vendor.reducer.js to add the final piece of our code in the reducer.</p><p>_reducers/vendor.reducer.js</p><pre>const initialState = { <br>    anchor: &#39;left&#39;,<br>    vendor: [],<br>    open: false,<br>    id: &#39;&#39;,<br>    name: &#39;&#39;,<br>    mobile: &#39;&#39;,<br>    phone_number: &#39;&#39;,<br>    address: &#39;&#39;<br>};</pre><pre>export function vendor(state = initialState, action) {<br>    switch (action.type) {<br>        case &#39;FETECHED_ALL_VENDOR&#39;:<br>            return {<br>                ...state,<br>                vendor: action.vendor<br>            };<br>        case &#39;VENDOR_DETAIL&#39;:<br>            return {<br>                ...state,<br>                id: action.id,<br>                name: action.name,<br>                mobile: action.mobile,<br>                phone_number: action.phone_number,<br>                address: action.address<br>            };<br>        case &quot;USER_UPDATED&quot;:<br>            return state;<br>        case &quot;HANDLE_ON_CHANGE&quot;:<br>            return {<br>                ...state,<br>                [action.props]: action.value<br>            };<br>        default:<br>            return state<br>        }<br>}</pre><p>In &#39;FETECHED_ALL_VENDOR&#39; case, we set vendor state with the result of all vendor details for displaying the grid.</p><p>In &#39;VENDOR_DETAIL&#39; case, we set values for id, name, mobile, phone_number and address to display the individual details of a selected vendor in edit mode.</p><p>In &#39;HANDLE_ON_CHANGE&#39; case, we set the values of props which changes. Suppose if only name is changes in the form, we need to set only the name state with the latest value without altering other state values, like return { ... state, name: action.name} . Since we can’t write a separate case for each props, we handle it by dynamically setting the state for the prop which are getting changed. <strong>Having said that, we have completed our </strong><strong>CRUD Application.</strong></p><p>We can test Insert, Edit and Delete by starting with adding new Vendor details.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ELvHXdbe3fUNzPq71ryGIg.png" /></figure><p>After Insert</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fech2gI5zi6P1C%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fbatman-joker-the-ech2gI5zi6P1C&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fech2gI5zi6P1C%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="223" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe3cc55485244b4e81d56cb50269d61a/href">https://medium.com/media/fe3cc55485244b4e81d56cb50269d61a/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1d-Ib7N9Ky79-FlxCrji9g.png" /></figure><p>Now, let’s try editing a vendor details</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ykYELC5CzGRCTmBQS26bwg.png" /></figure><p>You can notice that URL has the id which we are editing. Clicking on Save will save the changes.</p><p>Also clicking on the delete icon on the table will delete that record and update the table view.</p><p>That conclude our two part series on A Simple CRUD Application with Login On React + Redux + Axios + Nodejs REST API + MongoDB.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F1485wMdlDLG7mg%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2F1485wMdlDLG7mg&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F1485wMdlDLG7mg%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="248" frameborder="0" scrolling="no"><a href="https://medium.com/media/2afec4ed965e1ec15259a842f10780cd/href">https://medium.com/media/2afec4ed965e1ec15259a842f10780cd/href</a></iframe><p>Hope it was useful. I will attach the link to the github code for reference. If you have any doubt you can comment, I will try to answer.</p><p><a href="https://github.com/emanuelraj/vendor-crud-react-redux-medium-post">emanuelraj/vendor-crud-react-redux-medium-post</a></p><p>If you find that something is not explained correctly, please do comment so that I can correct it. Like I said at the start of the series, I am new to react and redux, the tutorial is based on my current understanding. This article may change over the course of time.</p><p>Thanks!!!</p><p>Happy Coding!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=376606eb67a7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Simple CRUD Application with Login On React + Redux + Axios + Nodejs REST API + MongoDB — Part I]]></title>
            <link>https://medium.com/@raju.allen/a-simple-crud-application-with-login-on-react-redux-axios-nodejs-rest-api-mongodb-part-i-af9c534251b?source=rss-2981354d3021------2</link>
            <guid isPermaLink="false">https://medium.com/p/af9c534251b</guid>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[axios]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Emanuel Raj]]></dc:creator>
            <pubDate>Wed, 15 Aug 2018 12:05:07 GMT</pubDate>
            <atom:updated>2018-08-29T08:06:25.468Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*ctFfwgFKSwGu1SYHHQN3-w.jpeg" /></figure><p>Hi All, Before we jump into the actual example let me give a quick intro about why I decided to write an article on a simple CRUD application using React and Redux.</p><p>I’m relatively new to React and Redux. When i’m trying to develop a small CRUD application with React and Redux involving login authentication and Route handling, I find hard to get good examples on Redux Login and Private Routing along with simple CRUD using Axios all at one place. Hence i decided to write an article on Developing a sample application on the same. This series also has REST API using Nodejs with MongoDB</p><p>There are plenty of articles and examples on What is React and What is Redux. If you are reading this series, I presume that you already know what is react and redux and you are looking for a guidance in putting things together and that is what we are going to do straight away.</p><p>In Part 1 of this series, I will focus developing a CRUD in Nodejs. I will be using MongoDB to store the data. Expressjs as Node framework. JWT to handle authentication.</p><p>In Part 2 of this series, I will develop Web APP in React and consume the API’s we exposed in Part 1.</p><p>This article may get updated from time to time. Like I said, at the time of writing this article, I’m relatively new to React and Redux.</p><p>So, Let’s get started.</p><h3><strong>Part 1 — Developing REST API using Nodejs + MongoDB</strong></h3><p><strong>Prerequisites</strong></p><p>You should have the following installed in your system.</p><ol><li>Nodejs</li><li>NPM</li><li>MongoDB</li></ol><p>Let’s first create a empty repository for our application.</p><pre>mkdir vendor-crud-sample<br>cd vendor-crud-sample/<br>npm init</pre><p>the above 3 commands will help you create a repo and then setup basic package.json file for our expressjs application.</p><p>Let’s start installing the basic packages needed.</p><ol><li>express — A Web Application framework for Nodejs</li><li>body-parser — To handle middleware</li><li>Mongoose — ODM Library for MongoDB</li><li>JWT — Handling Token based Authentication</li><li>CORS — Package to handle Cross Origin Requests</li><li>bcryptjs — For hashing the password.</li><li>morgan — For logging incoming requests.</li><li>compression — For compressing response body of all request which passes through this middleware</li></ol><p>I will be installing few other packages as we go along.</p><pre>npm install --save express mongoose jsonwebtoken cors bcryptjs morgan compression body-parser</pre><p>A gentle reminder before we proceed, I have renamed the index.js file to app.js</p><p>Now, before we add further lines of code, we need to create config file, to store environmental variables.</p><p>Let’s create a config directory in our root directory. Now we will create express.js file to import the installed packages.</p><p>config/express.js</p><pre>/**<br>* Express configuration<br>*/</pre><pre>&#39;use strict&#39;;</pre><pre>const express = require(&#39;express&#39;);<br>const morgan = require(&#39;morgan&#39;);<br>const compression = require(&#39;compression&#39;);<br>const bodyParser = require(&#39;body-parser&#39;);<br>const cors = require(&#39;cors&#39;);<br>const errorHandler = require(&#39;errorhandler&#39;);<br></pre><pre>module.exports = function(app) {<br>     const env = app.get(&#39;env&#39;);<br>     // **ALLOW CORS**** WARN: NOT SECURE<br>     app.use(cors());<br>     app.use(compression());<br>     app.use(bodyParser.urlencoded({ extended: false, limit: &#39;50mb&#39; }));<br>     app.use(bodyParser.json({ limit: &#39;50mb&#39; }));</pre><pre>     if (&#39;development&#39; === env || &#39;test&#39; === env) {<br>         app.use(morgan(&#39;dev&#39;));<br>         app.use(errorHandler()); // Error handler - has to be last<br>     }<br>};</pre><p>Note that we have used errorHandler so let’s go ahead and install that package.</p><pre>npm install --save errorhandler</pre><p>We will also create local.env.js and add the following code to store secret key for hashing tokens and URL for MongogDB connection.</p><p>config/local.env.js</p><pre>&#39;use strict&#39;;</pre><pre>module.exports = {<br>     secrets: {<br>           session: &quot;vendor-erp&quot;,        <br>           expiresIn: 2629746000     <br>     },<br>     db:{<br>         URI: &#39;mongodb://localhost:27017/vendor_erp&#39;<br>     }<br>}</pre><p>Now we will create a directory called environment inside config directory and create production.js , test.js, development.js to hold environment based config information.</p><p>config/environment/index.js</p><pre>&#39;use strict&#39;;</pre><pre>const path = require(&#39;path&#39;);<br>const _ = require(&#39;lodash&#39;);<br>const local = require(&#39;../local.env.js&#39;);</pre><pre>if (!process.env.VENDOR_NODE_ENV) {<br>      console.log(&quot;Environment Not Set. Please set VENDOR_NODE_ENV to development | test&quot;);<br>      requiredProcessEnv(VENDOR_NODE_ENV);<br>      process.exit(2);<br>}</pre><pre><br>function requiredProcessEnv(name) {<br>      if (!process.env[name]) {<br>           throw new Error(&#39;You must set the &#39; + name + &#39; environment variable&#39;);<br>     }<br>     return process.env[name];<br>}</pre><pre>// All configurations will extend these options<br>// ============================================</pre><pre>let config = {<br>      env: process.env.VENDOR_NODE_ENV,<br>      <br>      // Root path of server<br>      root: path.normalize(__dirname + &#39;/../../..&#39;),<br>      <br>      // Server port<br>      port: process.env.PORT || 8000,<br>      <br>      // Server IP<br>      ip: process.env.IP || &#39;0.0.0.0&#39;,</pre><pre>      // Should we populate the DB with sample data?<br>      seedDB: false,</pre><pre>      mongo: {<br>           options: {<br>                useNewUrlParser: true<br>           }<br>      },</pre><pre>      selfDomain: &quot;erpfs.com&quot;,</pre><pre>};</pre><pre>// Export the config object based on the VENDOR_NODE_ENV<br>// ==============================================</pre><pre>module.exports = _.merge(<br>       config,<br>       require(&#39;./&#39; + process.env.VENDOR_NODE_ENV + &#39;.js&#39;) || {},<br>       require(&#39;../local.env.js&#39;));</pre><p>so we have set up common config file with env, root, ip, port, mongo options. When ever we run the application it is mandatory to mention which environment the application is running by setting value for VENDOR_NODE_ENV either to any one of these test/production/developmemt. If not provided, we will set development as default in app.js</p><p>note that we have used _.merge of lodash and path.normalize of path packages so let’s go ahead and install those packages.</p><pre>npm install --save path lodash</pre><p>Now, we will extend the those environment variables and modify it for each environment.</p><p>config/environment/development.js</p><pre>&#39;use strict&#39;;</pre><pre>let local = require(&#39;../local.env.js&#39;);</pre><pre>// Development specific configuration<br>// ==================================</pre><pre>module.exports = {<br>     selfURL: &#39;http://localhost:8000&#39;,<br>     // Control debug level for modules using visionmedia/debug<br>     DEBUG: &#39;&#39;,<br>     port: 8001,<br>     ip: &#39;0.0.0.0&#39;,<br>     seedDB: true,<br>     webApp: {<br>        url: &quot;http://localhost:80&quot;<br>     }<br>};</pre><p>If you notice here, I’m extending and changing the port from default 8000 to 8001and setting seedDB to true. By setting these values in development.js, whenever the application is started in development mode, the application runs at 8001 port and it will seed default value.</p><p>config/environment/test.js</p><pre>&#39;use strict&#39;;</pre><pre>let local = require(&#39;../local.env.js&#39;);</pre><pre>// Test specific configuration<br>// =================================</pre><pre>module.exports = {</pre><pre>     // Server IP<br>     ip: &#39;0.0.0.0&#39;,</pre><pre>     // Control debug level for modules using visionmedia/debug<br>     DEBUG: &#39;&#39;,</pre><pre>     // Server port<br>     port: 8080,</pre><pre>     // MongoDB connection options<br>     mongo: {<br>         uri: &#39;mongodb://localhost:27017/vendor_test_erp&#39;<br>     },</pre><pre>     selfURL: &#39;http://localhost&#39;,</pre><pre>     webApp: {<br>          url: &quot;http://loaclhost:80&quot;<br>     }<br>};</pre><p>Note, we have changed the mongo uri , so that when the application runs on test environment, it uses vendor_test_erp collection.</p><p>config/environment/production.js</p><pre>&#39;use strict&#39;;</pre><pre>let local = require(&#39;../local.env.js&#39;);</pre><pre>// Production specific configuration<br>// =================================</pre><pre>module.exports = {<br>     // Server IP<br>     ip: process.env.IP ||undefined,</pre><pre>     // Control debug level for modules using visionmedia/debug<br>     DEBUG: &#39;&#39;,</pre><pre>     // Server port<br>     port: 8080,</pre><pre>     mongo: {<br>          uri: local.mongo.uri<br>     },</pre><pre>     selfURL: &#39;http://localhost&#39;,<br>     webApp: {<br>          url: &quot;http://localhost:80&quot;<br>     }<br>};</pre><p>Also, we need to add seed file, to seed default values. Let’s add that file outside environment directory. for now, let’s keep that file empty.</p><p>config/seed.js</p><p>So, at the end of this, your config directory should look like this.</p><pre>config<br>     |__ express.js<br>     |__ local.env.js<br>     |__ seed.js<br>     |__ environment/<br>           |__ index.js<br>           |__ development.js<br>           |__ production.js<br>           |__ test.js</pre><p>Alright, we have setup the needed environment config. Now, we jump into creation of basic node server.</p><p>app.js</p><pre>/**<br>* Main application file<br>*/</pre><pre>&#39;use strict&#39;;</pre><pre>// Set default node environment to development</pre><pre>process.env.VENDOR_NODE_ENV = process.env.VENDOR_NODE_ENV || &#39;development&#39;;</pre><pre><br>const express = require(&#39;express&#39;);<br>const config = require(&#39;./config/environment&#39;);<br>const mongoose = require(&#39;mongoose&#39;);</pre><pre>//Connect to database<br>mongoose.Promise = global.Promise;<br>mongoose.connect(config.db.URI, config.mongo.options);<br>mongoose.connection.on(&#39;error&#39;, function (err) {<br>       console.error(&#39;MongoDB connection error: &#39; + err);<br>       process.exit(-1);<br>});</pre><pre>const app = express();<br>const server = require(&#39;http&#39;).createServer(app);<br>require(&#39;./config/express&#39;)(app);<br>require(&#39;./config/seed&#39;);</pre><pre><br>// Start server<br>server.listen(config.port, config.ip, function() {<br>        console.log(&#39;Express server listening on %d, in %s mode&#39;, config.port, app.get(&#39;env&#39;));</pre><pre>});</pre><pre>// Expose app<br>exports = module.exports = app;</pre><p>Note, that we are checking for VENDOR_NODE_ENV , if not found, setting the environment to development by default. Also, i have imported config/seed to seed the database when the application is launched. We will populate the seed file once we create users collection.</p><p>Now then, we are all set to run our nodejs server. I use nodemon npm package to run nodejs application in development. This helps to avoid the pain of restarting the server whenever we make changes to our application.</p><pre>npm install -g nodemon</pre><p>We need to install nodemon package globally, so that we can reuse nodemon in all our other node development.</p><p>So here we are, let’s run the application.</p><pre>nodemon start app.js<br>[nodemon] 1.17.5<br>[nodemon] to restart at any time, enter `rs`<br>[nodemon] watching: *.*<br>[nodemon] starting `node start app.js`<br>Express server listening on 8001, in development mode</pre><p>There you go!! our express server started at port 8001 in development mode.</p><p>We have successfully run the basic nodejs server with all the necessary skeleton in the form of config. Although the scope of this series is to just build a basic CRUD, you can basically use the skeleton to build enterprise applications.</p><p>Fasten your seat belts, lets build the Vendor CRUD!!!</p><p>Hold on!!!</p><p>Before we proceed to create Vendor CRUD, we will create user and then handle basic authentication with JWT.</p><p>So let’s go ahead and create user schema using mongoose.</p><p>api/users/users.model.js</p><pre>&#39;use strict&#39;;</pre><pre>const mongoose = require(&#39;mongoose&#39;);<br>const Schema = mongoose.Schema;<br>const DEFAULTPASSWORD = &#39;vendoradmin&#39;;<br>const bcrypt = require(&#39;bcryptjs&#39;);</pre><pre>const UserSchema = new Schema({<br>    name : {<br>        type: String<br>    },<br>    username : {<br>       type: String,<br>       required: true<br>    },<br>    password : {<br>       type: String,<br>       required: true<br>    },<br>    is_active: {<br>       type: Boolean,<br>       default: true<br>    }<br>},{<br>    id: false,<br>    toObject: {<br>        virtuals: true,<br>        getters: true<br>    },<br>    toJSON: {<br>        virtuals: true,<br>        getters: true,<br>        setters: false<br>    },<br>    timestamps: true<br>});</pre><pre>UserSchema.pre(&#39;find&#39;, function () {<br>     this.where({ is_active: { $ne: false } });<br>});</pre><pre>var validatePresenceOf = function (value) {<br>     return value &amp;&amp; value.length;<br>};</pre><pre>/**<br>* Pre-save hook<br>*/</pre><pre>UserSchema<br>.pre(&#39;save&#39;, function (next) {<br>     if (!this.isNew) return next();<br>     if (!validatePresenceOf(this.password)) {<br>         next()<br>     } else {<br>         this.newPassword = this.password || DEFAULTPASSWORD;<br>         this.password = bcrypt.hashSync(this.newPassword, 8);<br>         return next();<br>     }<br>});</pre><pre>module.exports = mongoose.model(&#39;User&#39;, UserSchema);</pre><p>Now we will go to that empty seed file and add the default user.</p><p>config/seed.js</p><pre>/**<br>* Populate DB with sample data on server start<br>* to disable, edit config/environment/index.js, and set `seedDB: false`<br>*/</pre><pre>&#39;use strict&#39;;</pre><pre>// Insert seed models below<br>var User = require(&#39;../api/users/users.model&#39;);</pre><pre>User.countDocuments({}).exec((err, count) =&gt; {<br>    if (err) {<br>         console.error(err);<br>         return;<br>    }</pre><pre>    if (count == 0) {<br>       User.create({<br>            name : &#39;Allen&#39;,<br>            username : &#39;allen&#39;,<br>            password : &#39;vendoradmin&#39;<br>       }, (err, seedUser) =&gt; {<br>            if (err) {<br>                console.error(err);<br>                return;<br>            }<br>           console.log(&quot;Seed superuser created&quot;);<br>       })<br>    }<br>})</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FlgRNj0m1oORfW%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2FlgRNj0m1oORfW&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FlgRNj0m1oORfW%2Fgiphy-downsized-large.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="242" frameborder="0" scrolling="no"><a href="https://medium.com/media/f28ae60cdc5aeef6c1333374266a9e80/href">https://medium.com/media/f28ae60cdc5aeef6c1333374266a9e80/href</a></iframe><p>Now take a look at the console, you can see the power of nodemon.</p><pre>[nodemon] restarting due to changes...<br>[nodemon] starting `node start app.js`<br>Express server listening on 8001, in development mode<br>Seed superuser created</pre><p>Nodemon automatically restarted the server once you save the changes and guess what, we have successfully seeded the superuser as well.</p><p>Now, we have created user model and inserted a user. Let’s add authentication layer of our application.</p><p>api/auths/auths.controller.js</p><pre>&#39;use strict&#39;;</pre><pre>const jwt = require(&#39;jsonwebtoken&#39;);<br>const config = require(&#39;../../config/environment&#39;);<br>const User = require(&#39;../users/users.model&#39;);<br>const bcrypt = require(&#39;bcryptjs&#39;);</pre><pre><br>module.exports = {<br>      login: (req, res) =&gt; {<br>            User.findOne({username : req.body.username},function(err, user){<br>               if(err){<br>                   return res.status(401).json({message : err});<br>               }</pre><pre>               var isPasswordValid = bcrypt.compareSync(req.body.password, user.password);</pre><pre>if(!isPasswordValid){<br>                     return res.status(401).json({auth : false, token : null, message : &quot;Not Authorised User&quot;});<br>               }else{<br>                     let payload = {<br>                         user_id : user._id,<br>                         username : user.username<br>                     }<br>                     let token = jwt.sign(payload, config.secrets.session,{expiresIn : config.secrets.expiresIn});</pre><pre>                    return res.status(200).json({auth : true, token : token, message : &quot;User Logged In Successfully&quot;});<br>              }<br>          });<br>     }</pre><pre>}</pre><p>we have written a code to validate password using bcrypt.compare to check the password entered by the user is same as the encrypted password. Since we are using bcrypt to perform one way hashing we will compare the encrypted password.</p><p>We are also using sign() method of jsonwebtoken to generate token for authentication in the future API Calls.</p><p>Speaking of API Calls, we need to expose this method to the outside world with the help of routes. Let’s start by creating a routes.js file and add our base url.</p><p>routes.js</p><pre>/**<br>* Main application routes<br>*/</pre><pre>&#39;use strict&#39;;</pre><pre>module.exports = function(app) {<br>     app.use(&#39;/api/v1/auths&#39;, require(&#39;./api/auths&#39;));<br>};</pre><p>We need to add relative routing inside respective modules. So let’s add index.js file inside aip/auths/ to handle relative routing.</p><p>/api/auths/index.js</p><pre>&#39;use strict&#39;;</pre><pre>const express = require(&#39;express&#39;);<br>const controller = require(&#39;./auths.controller&#39;);<br>const router = express.Router();</pre><pre>router.post(&#39;/&#39;, controller.login);</pre><pre>module.exports = router;</pre><p>When the relative /endpoint with post method is called, it will redirect the request to login method inside auth.controller</p><p>Alright!! We still have one more final bit of code change needed. We need to tell the app.js file to use routes.js file when the application is launched. So let’s go ahead and make that change.</p><p>app.js add the following line</p><pre>require(&#39;./routes&#39;)(app);</pre><p>so your app.js code snippet should look something like this.</p><pre>...<br>const server = require(&#39;http&#39;).createServer(app);<br>require(&#39;./config/express&#39;)(app);<br>require(&#39;./routes&#39;)(app);<br>require(&#39;./config/seed&#39;);<br>...</pre><p>So, We have put together all pieces and we even written our first API. let’s go and test our Login API .</p><p>I use POSTMAN REST Client for testing the API’s.</p><p>I select Method as Post and the url endpoint will be. https://localhost:8001/api/v1/auths/ . Also we need to pass the username and password as json body.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_bs5g94CSpc7z4jAIcnDKQ.png" /></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Ftenor.com%2Fembed%2F5863708&amp;url=https%3A%2F%2Ftenor.com%2Fview%2Fcyborg-booyah-teen-titans-gif-5863708&amp;image=https%3A%2F%2Fmedia.tenor.com%2Fimages%2Fff7468095b8e5c5716e518a422e9ecdc%2Ftenor.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=tenor" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/4b0ab63e2d746b362ed239bb6a6e6e82/href">https://medium.com/media/4b0ab63e2d746b362ed239bb6a6e6e82/href</a></iframe><p>Boo-yah!!!! Our Login API works and returns a token which we need to use for the remaining API Calls.</p><p>We are into the final building block of our Vendor CRUD application.</p><p>We can start by creating Vendor Schema inside a new repository called vendors</p><p>api/vendors/vendors.model.js</p><pre>&#39;use strict&#39;;</pre><pre>const mongoose = require(&#39;mongoose&#39;);<br>const Schema = mongoose.Schema;</pre><pre>const VendorSchema = new Schema({<br>      name : {<br>         type: String,<br>         required: true<br>      },<br>      address : {<br>         type: String<br>      },<br>      phone_number : {<br>         type: String<br>      },<br>      mobile : {<br>         type: String<br>      },<br>      is_active : {<br>         type: Boolean,<br>         default: true<br>      }<br>},{<br>     id: false,<br>     toObject: {<br>         virtuals: true,<br>         getters: true<br>     },<br>     toJSON: {<br>         virtuals: true,<br>         getters: true,<br>         setters: false<br>     },<br>     timestamps: true<br>});</pre><pre><br>VendorSchema.pre(&#39;find&#39;, function () {<br>     this.where({ is_active: { $ne: false } });<br>});</pre><pre>module.exports = mongoose.model(&#39;Vendor&#39;, VendorSchema);</pre><p>We add vendors.controller.js file to handle our CRUD operation. We need 5 methods to perform CRUD.</p><ol><li>index — To get all vendors details, for displaying grid in the React Application.</li><li>retrieve — To get individual vendor detail for edit.</li><li>create — To save new vendor details.</li><li>update — To update vendor details when we click save after edit the values from React app.</li><li>delete — To delete particular vendor details, kindly note that we will perform only soft delete, so we will be setting the is_active field to false.</li></ol><p>api/vendors/vendors.controller.js</p><pre>&#39;use strict&#39;;</pre><pre><br>const Vendor = require(&#39;../vendors/vendors.model&#39;);</pre><pre><br>module.exports = {<br>      index: (req, res) =&gt; {<br>          Vendor<br>          .find({})<br>          .exec((err, vendorDetails)=&gt;{<br>               if (err) {<br>                   res.status(500).json({message : err})<br>               }</pre><pre>res.status(200).json({ message: &quot;Vendor Details fetched Successfully&quot;, data : vendorDetails});<br>          })<br>      },<br>      retrieve: (req, res) =&gt; {<br>           const vendorId = req.params.id;<br>           Vendor<br>           .findOne({_id:vendorId})<br>           .exec((err, vendorDetails)=&gt;{<br>                if (err) {<br>                    res.status(500).json({message : err})<br>                }<br>                <br>                res.status(200).json({ message: &quot;Vendor Details fetched Successfully&quot;, data : vendorDetails});<br>           })<br>       },<br>       create: (req, res) =&gt; {<br>           Vendor.create(req.body, (err, vendorDetails) =&gt; {<br>                if (err) {<br>                     res.status(500).json({message : err})<br>                }</pre><pre>                res.status(201).json({ message: &quot;Vendor Created Successfully&quot;, data : vendorDetails});<br>           })<br>       },<br>       update: (req, res)=&gt;{<br>            const vendorId = req.params.id;<br>            Vendor<br>            .findByIdAndUpdate(vendorId, { $set: req.body })<br>            .exec((err, vendorDetails) =&gt; {<br>                 if (err) res.status(500).json({message : err})</pre><pre>                 res.status(200).json({ message: &quot;Vendor updated&quot;});</pre><pre>            })<br>       },<br>       delete: (req, res)=&gt;{<br>            const vendorId = req.params.id;<br>            Vendor<br>            .findByIdAndUpdate(vendorId, { $set: { is_active: false}})<br>            .exec((err, vendorDetails) =&gt; {<br>                 if (err) res.status(500).json({message : err})<br>            <br>                 res.status(200).json({ message: &quot;Vendor Deleted&quot;});<br>             })<br>       }<br>}</pre><p>We have added the code to perform CRUD operation, all we need now is to expose these methods through routing. So we will add a index.js file inside vendors directory and then add the base url in routes.js</p><p>api/vendors/index.js</p><pre>&#39;use strict&#39;;</pre><pre>const express = require(&#39;express&#39;);<br>const controller = require(&#39;./vendors.controller&#39;);<br>const router = express.Router();</pre><pre>router.get(&#39;/&#39;, controller.index);<br>router.get(&#39;/:id&#39;, controller.retrieve);<br>router.post(&#39;/&#39;, controller.create);<br>router.put(&#39;/:id&#39;, controller.update);<br>router.delete(&#39;/:id&#39;, controller.delete);</pre><pre><br>module.exports = router;</pre><p>Add the base url in routes.js . After adding vendor base url, the routes.js looks like below.</p><pre>/**<br>* Main application routes<br>*/</pre><pre>&#39;use strict&#39;;</pre><pre>module.exports = function(app) {<br>       app.use(&#39;/api/v1/auths&#39;, require(&#39;./api/auths&#39;));<br>       app.use(&#39;/api/v1/vendors&#39;, require(&#39;./api/vendors&#39;));<br>};</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fl0Iy69RBwtdmvwkIo%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Freactionseditor-l0Iy69RBwtdmvwkIo&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fl0Iy69RBwtdmvwkIo%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="350" frameborder="0" scrolling="no"><a href="https://medium.com/media/dd613df9fcdf13bba926186710229cbc/href">https://medium.com/media/dd613df9fcdf13bba926186710229cbc/href</a></iframe><p>We are Almost, Almost done with our Part 1 of this series. We need to add a middleware to handle Authentication.</p><p>api/auths/verifyToken.js</p><pre>var express = require(&#39;express&#39;);<br>var jwt = require(&#39;jsonwebtoken&#39;);<br>var config = require(&#39;../../config/environment&#39;);<br>var VerifyToken = express.Router();</pre><pre>VerifyToken.use(function(req, res, next){<br>      var token = req.headers[&#39;x-access-token&#39;];<br>      if(!token){<br>          return res.status(403).json({auth: false, message: &quot;No Token&quot;});<br>      }</pre><pre>      jwt.verify(token, config.secret, function(err, decoded){<br>          if(err){<br>               return res.status(401).json({auth: false, message: &quot;Not An Authorized User&quot;});<br>          }<br>    <br>          req.body.user_id = decoded.user_id;<br>          req.body.username = decoded.username;<br>          next();<br>      });<br>});</pre><pre>module.exports = VerifyToken;</pre><p>Now all we need to do is use this middleware in the vendor’s routing to check user is Authenticated to access vendor information.</p><p>after adding VerifyToken middleware, our api/vendors/index.js file looks like the following.</p><p>api/vendors/index.js</p><pre>&#39;use strict&#39;;</pre><pre>const express = require(&#39;express&#39;);<br>const controller = require(&#39;./vendors.controller&#39;);<br>const router = express.Router();<br>const VerifyToken = require(&#39;../auths/verifyToken&#39;);<br></pre><pre>router.get(&#39;/&#39;, VerifyToken, controller.index);<br>router.get(&#39;/:id&#39;, VerifyToken, controller.retrieve);<br>router.post(&#39;/&#39;, VerifyToken, controller.create);<br>router.put(&#39;/:id&#39;, VerifyToken, controller.update);<br>router.delete(&#39;/:id&#39;, VerifyToken, controller.delete);</pre><pre>module.exports = router;</pre><p>DONE!!!! Lets test Get All vendor API without Token.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PWzaXgtz--dxIhHB-2zPzQ.png" /></figure><p>Great!!! We Got the status code 403 and message “No Token”.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FubGdLIN4zBKHm%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2FubGdLIN4zBKHm&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FubGdLIN4zBKHm%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="326" frameborder="0" scrolling="no"><a href="https://medium.com/media/3e7b1ca6be7651b62ce4cf43755b9392/href">https://medium.com/media/3e7b1ca6be7651b62ce4cf43755b9392/href</a></iframe><p>Let’s add the token and hit the same API. We will add our custom header x-access-token and add the token we received on the successful login.</p><p>Now, Let’s try the same API call with token. we expect to get empty data, since we are yet to insert Vendor details.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ASHeG_f8sJCaH0tYIDDjeQ.png" /></figure><p>Now, We will insert a Vendor Detail using post method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o8P8vvtnsiJXFHAGP9ywWA.png" /></figure><p>Let’s go back and again test our Get All Vendor Details API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GMkf9_0T3fqD5TinIFdOBQ.png" /></figure><p>Now let’s try retrieve method, for that we need to pass _id of a particular vendor as params in get method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*doEINNSh-PSzTOzNmtzP8g.png" /></figure><p>Let edit the value and test the update method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3Ccomia6Hd1oswE4bZEP1w.png" /></figure><p><strong>Finally!!!!!</strong> Let’s test our final method delete.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*74YK2fEGM0iDW0OJST0VPA.png" /></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FITnn2IenMv7SE%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fcatwoman-leaving-ITnn2IenMv7SE&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FITnn2IenMv7SE%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="234" frameborder="0" scrolling="no"><a href="https://medium.com/media/f17f8cd497cd1b863f11d5c36ffc12d9/href">https://medium.com/media/f17f8cd497cd1b863f11d5c36ffc12d9/href</a></iframe><p>That brings the end of the Part 1 of two part series on A Simple CRUD Application with Login On React + Redux + Axios + Nodejs REST API + MongoDB.</p><p>I have attached link to github source code and Postman document for the API.</p><ol><li><a href="https://github.com/emanuelraj/vendor-crud-sample-medium-post">https://github.com/emanuelraj/vendor-crud-sample-medium-post</a></li><li><a href="https://documenter.getpostman.com/view/4484782/RWTmvyND">https://documenter.getpostman.com/view/4484782/RWTmvyND</a></li></ol><p>See you on <a href="https://medium.com/@raju.allen/a-simple-crud-application-with-login-on-react-redux-axios-nodejs-rest-api-mongodb-part-ii-376606eb67a7">Part 2</a> of the series. Until then.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F3oEjHSNWEQN0DbSULu%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Flionsgatehomeent-arnold-schwarzenegger-terminator-2-hasta-la-vista-3oEjHSNWEQN0DbSULu&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F3oEjHSNWEQN0DbSULu%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="435" frameborder="0" scrolling="no"><a href="https://medium.com/media/15a62d8a9cc3eb82a92ba256476da086/href">https://medium.com/media/15a62d8a9cc3eb82a92ba256476da086/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af9c534251b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>