Post Method with React and redux

Viewed 196

I have a simple app for CRUD operations, now I can delete, edit, and display data, but I want to add new items to a list of users fetched from API(JSON server fake API) using react and redux.

Now when I click add user and save the data only id is sent but other data are not sent.

enter image description here

here is a live demo: Redux live demo with source code sandbox .

Here is my form, AddUserForm.js

import React, { useState } from 'react'
import {useDispatch} from 'react-redux'
import { addNewUser  } from '../redux/acitons/users/Users';

function AddUserForm({users}) {
    const dispatch = useDispatch();
    const [newUserName, setNewUserName] = useState('');

   const handleSubmit = (e) =>{
    e.preventDefault();

    const usersList = users;
    const newUserId = usersList[usersList.length - 1].id + 1;

    console.log("your name", newUserName);
    console.log("your id", newUserId)

    dispatch(addNewUser({
      ...users,
      id: newUserId,
      name: newUserName,
    }));

   }

  const handleCancel = () => {};
  return (
    <tr>
      <td>{newUserName.id}</td>
      <td>
        <input
          value={newUserName}
          name="name"
          onChange={e => setNewUserName(e.target.value)}
        />
      </td>
      <td>
        <button type="button" className="btn outline" onClick={handleCancel}>
          <i className="material-icons">Cancel</i>
        </button>
        <button
          type="button"
          className="btn btn-success btn-link"
          onClick={handleSubmit}
        >
          <i className="material-icons">save</i>
        </button>
      </td>
    </tr>
  );
}

export default AddUserForm

and I call like this in parent components with the on click button.

{adding && <>
            <AddUserForm addNewUser={addNewUser} users={userData.users} />
   </>}

Here is a button in the parent components.

<button
          type="button"
          className="btn btn-success btn-link btn-add"
          onClick={() => setAdding(true)}
        >
    <i className="material-icons">Add user</i>
</button>

What is wrong with my code? any help or suggestions will be appreciated.

1 Answers

In the debugging tools screenshot you are showing us the response body, not the request body.

users is an array, why this

dispatch(addNewUser({
  ...users,
  id: newUserId,
  name: newUserName,
}));

intead of this?

dispatch(addNewUser({
  id: newUserId,
  name: newUserName,
}));

The root cause of the problem is in src/redux/acitons/users/Users

export const addNewUser = data => {

  console.log("adding mother a new user", data);

  return dispatch => {
    axios.post("http://localhost:3000/users")

Just change last line in

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

I can see data in the console.log not in the POST.

This gives error with empty usersList.

const newUserId = usersList[usersList.length - 1].id + 1;

Hope this helps.

Related