Search code examples
expressreactjsreduxrethinkdbaxios

Sending params from React/Redux App with Axios


I'm struggling to understand how to get params into an axios.post request? A little about my app(s) so far:

I have an express app that is talking to an instance of RethinkDB. I also have a React/Redux App that is separate. I can successfully hit my express endpoint with an axios.get in my action creators and show that data(users) in a React Component. However, now I'm trying to send params over to another route in my express app and have it save that user in the rethinkdb database. I'm not concerned with authentication for the time being. I have it setup on the express side correctly and can save a dummy user to the DB from within the express app via curl, but I don't know how to SEND the needed params over with the request from the react app/react form. Please find below some relevant code.

From my Express App API, which when hit manually successfully saves the test user to the database.

var TestUser = thinky.createModel("TestUser", {
  id: String,
  name: String,
  email: String,
})

router.get('/newUser', (req, res) => {
  TestUser.save({
    name: 'sawyer',
    email: '[email protected]'
  }).then((result) => {
    console.log('Saved!')
    res.send(result)
  })
})

..and below is the code snippet from my actions file in the separate React and Redux App. To be honest i'm not really sure hot to write it and include the user object.

function addUser (user) {
  return {
    type: ADD_USER,
    user,
  }
}

export function addAndSaveUser (user) {
  return function (dispatch) {
    return dispatch(addUser(user)).then({
      axios.post("http://localhost:3000/users/newUser", )
    })
  }
}

Any help would be greatly appreciated.


Solution

  • Just pass user object as a second param

    axios.post("http://localhost:3000/users/newUser", user)
    

    And it's better to dispatch addUser action after you successfully created it.

    export function addAndSaveUser (user) {
      return function(dispatch) {
        axios.post("http://localhost:3000/users/newUser", user).then(res => {
          dispatch(addUser(res.data));
        });
      };
    }