title: How to generate a unique id automatically for the data that is posted to an API server using axios library in redux
body: <p>I have a redux-form which is used to receive data from the user and post it to a back-end API server.While posting data to the server,I want to generate a unique id for each set of data that is being posted to the server, so that I can use the id later for referencing that particular set and displaying it to the user.So,how to generate that unique id automatically while posting a set of data to the server?</p>
  
  <p>The code for my <strong>redux-form</strong> is given below:</p>
  
  <pre><code>import React, { Component } from 'react';
  import { Field, reduxForm } from 'redux-form';
  import { Link } from 'react-router-dom';
  import { connect } from 'react-redux';
  import { createPosts } from '../actions/posts_action';
  
  class CreatePost extends Component {
    constructor() {
      super();
      this.state = {
        selectValue : ''
    };
    this.handleChange = this.handleChange.bind(this);
    this.renderCategory = this.renderCategory.bind(this);
  }
  
    renderField(field) {
        return(
          &lt;div className="title-design"&gt;
              &lt;label className="label-design"&gt; {field.label} &lt;/label&gt;
              &lt;input
                type="text"
                className="title-input"
                {...field.input}
              /&gt;
              &lt;div className="text-help  has-danger"&gt;
                {field.meta.touched ? field.meta.error : ''}
              &lt;/div&gt;
        &lt;/div&gt;
        );
    }
  
    handleChange(e) {
      const value=e.target.value;
      this.props.change("categories",value);
      this.setState({selectValue: value}, () =&gt; {
        console.log(value)
      });
    }
  
    renderCategory(field) {
      return(
        &lt;div className="title-design"&gt;
          &lt;label className="label-design"&gt;{field.label} &lt;/label&gt;
            &lt;Field name="category" className="title-input" component="select"&gt;
              &lt;option&gt;&lt;/option&gt;
              &lt;option value="react"&gt;React&lt;/option&gt;
              &lt;option value="redux"&gt;Redux&lt;/option&gt;
              &lt;option value="udacity"&gt;Udacity&lt;/option&gt;
            &lt;/Field&gt;
  
            &lt;div className="text-help has-danger"&gt;
              {field.meta.touched ? field.meta.error : ''}
            &lt;/div&gt;
        &lt;/div&gt;
      );
    }
  
      onSubmit(values) {
        this.props.createPosts(values, () =&gt; {
            this.props.history.push('/');
        });
      }
  
  
  
      render() {
        const { handleSubmit } = this.props;
  
        return (
          &lt;form onSubmit={handleSubmit(this.onSubmit.bind(this))}&gt;
            &lt;Field
              label="Title for Post"
              name="title"
              component={this.renderField}
            /&gt;
  
            &lt;Field
              label="Post Content"
              name="body"
              component={this.renderField}
            /&gt;
  
            &lt;Field
              label="Category"
              name="category"
              component={this.renderCategory}
              /&gt;
  
  
  
            &lt;button type="submit" className="btn btn-primary"&gt;Submit&lt;/button&gt;
            &lt;Link  to="/"&gt;
              &lt;button className="cancel-button"&gt;Cancel&lt;/button&gt;
            &lt;/Link&gt;
          &lt;/form&gt;
        );
      }
  }
  
  function validate(values) {
    const errors = {} ;
  
    if (!values.title) {
        errors.title = "Enter a title";
    }
  
    if (!values.body) {
      errors.body = "Enter some content";
      }
  
    if(!values.category) {
      errors.category = "Please select a category";
    }
  
    if (!values.id) {
        errors.id = "ID not generated";
    }
  
    return errors;
  }
  
  export default reduxForm({
    validate : validate,          //validate
    form : 'CreatePostForm'
  })(
    connect(null,{ createPosts })(CreatePost)
  );
  </code></pre>
  
  <p>The <strong>action creator</strong> for creating a new post is given below:</p>
  
  <pre><code>//Action Creator for creating posts
  export function createPosts(values, callback) {
  
    return dispatch =&gt; {
      return axios.post(`${API}/posts`,values,{headers})
        .then((data) =&gt; {
          callback();
          console.log(data)
        dispatch({
          type: CREATE_POST,
          payload: data
        })
      })
    }
  }
  </code></pre>
  
  <p><strong>Reducer</strong> for creating the post:</p>
  
  <pre><code>import _ from 'lodash';
  import { FETCH_POSTS, FETCH_POST, CREATE_POST } from '../actions/posts_action';
  
  export default function(state = {}, action) {
    switch (action.type) {
      case FETCH_POST:
        // const post = action.payload.data;
        // const newState  = { ...state,  };
        // newState[post.id] = post;
        // return newState;
        return {...state, [action.payload.id]: action.payload};
  
      case FETCH_POSTS:
       return {posts: { ...state.posts, ...action.payload }};
  
      case CREATE_POST:
        return {posts: { ...state, ...action.payload}};
  
       default:
        return state;
    }
  
  }
  </code></pre>
  
  <p>So,how to genrate the id for each set of data that is sent to the server?</p>
  
  <p><strong>Edit 1:</strong></p>
  
  <p>I am trying to add the uuid on my onSubmit() method as shown below,but it doesn't work.I sit not how it should be done or I have to do it some other way?</p>
  
  <pre><code>  onSubmit(values) {
  
            this.props.createPosts(values, () =&gt; {
              uuidv1();
            this.props.history.push('/');
        });
      }
  </code></pre>
  
  <p><strong>Edit 2:</strong></p>
  
  <p>Sever file for posts: </p>
  
  <pre><code>const clone = require('clone')
  
  let db = {}
  
  const defaultData = {
    "8xf0y6ziyjabvozdd253nd": {
      id: '8xf0y6ziyjabvozdd253nd',
      timestamp: 1467166872634,
      title: 'Udacity is the best place to learn React',
      body: 'Everyone says so after all.',
      author: 'thingtwo',
      category: 'react',
      voteScore: 6,
      deleted: false,
      commentCount: 2
    },
    "6ni6ok3ym7mf1p33lnez": {
      id: '6ni6ok3ym7mf1p33lnez',
      timestamp: 1468479767190,
      title: 'Learn Redux in 10 minutes!',
      body: 'Just kidding. It takes more than 10 minutes to learn technology.',
      author: 'thingone',
      category: 'redux',
      voteScore: -5,
      deleted: false,
      commentCount: 0
    }
  }
  
  function getData (token) {
    let data = db[token]
    if (data == null) {
      data = db[token] = clone(defaultData)
    }
    return data
  }
  
  function getByCategory (token, category) {
    return new Promise((res) =&gt; {
      let posts = getData(token)
      let keys = Object.keys(posts)
      let filtered_keys = keys.filter(key =&gt; posts[key].category === category &amp;&amp; !posts[key].deleted)
      res(filtered_keys.map(key =&gt; posts[key]))
    })
  }
  
  function get (token, id) {
    return new Promise((res) =&gt; {
      const posts = getData(token)
      res(
        posts[id].deleted
          ? {}
          : posts[id]
      )
    })
  }
  
  function getAll (token) {
    return new Promise((res) =&gt; {
      const posts = getData(token)
      let keys = Object.keys(posts)
      let filtered_keys = keys.filter(key =&gt; !posts[key].deleted)
      res(filtered_keys.map(key =&gt; posts[key]))
    })
  }
  
  function add (token, post) {
    return new Promise((res) =&gt; {
      let posts = getData(token)
  
      posts[post.id] = {
        id: post.id,
        timestamp: post.timestamp,
        title: post.title,
        body: post.body,
        author: post.author,
        category: post.category,
        voteScore: 1,
        deleted: false,
        commentCount: 0
      }
  
      res(posts[post.id])
    })
  }
  
  function vote (token, id, option) {
    return new Promise((res) =&gt; {
      let posts = getData(token)
      post = posts[id]
      switch(option) {
          case "upVote":
              post.voteScore = post.voteScore + 1
              break
          case "downVote":
              post.voteScore = post.voteScore - 1
              break
          default:
              console.log(`posts.vote received incorrect parameter: ${option}`)
      }
      res(post)
    })
  }
  
  function disable (token, id) {
      return new Promise((res) =&gt; {
        let posts = getData(token)
        posts[id].deleted = true
        res(posts[id])
      })
  }
  
  function edit (token, id, post) {
      return new Promise((res) =&gt; {
          let posts = getData(token)
          for (prop in post) {
              posts[id][prop] = post[prop]
          }
          res(posts[id])
      })
  }
  
  function incrementCommentCounter(token, id, count) {
    const data = getData(token)
    if (data[id]) {
      data[id].commentCount += count
    }
  }
  
  module.exports = {
    get,
    getAll,
    getByCategory,
    add,
    vote,
    disable,
    edit,
    getAll,
    incrementCommentCounter
  }
  </code></pre>