React/redux: Not saving in state as intended

给你一囗甜甜゛ 提交于 2021-02-10 18:10:34

问题


I am building a review app. I am using json-server to do post request. My database looks like this

[{
    "id": 5,
    "name": "Tom Cruise",
    "image": "http://placeholder.pics/svg/300x200/000000",
    "title": "Hiring Manager",
    "employeeId": "22222222",
    "funFact": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.",
    "dateOfJoining": "04/12/2013"
  },
  {
    "id": 6,
    "name": "Julius Caesar",
    "image": "http://placeholder.pics/svg/300x200/fdfdfd",
    "title": "Sales Executive",
    "employeeId": "33333333",
    "funFact": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.",
    "dateOfJoining": "04/12/2016"
  }
]

Here is my add Action

//Add Employee
export const addEmployee = employeeData => dispatch => {
  axios
    .post("http://localhost:3004/employees", {
      employeeData,
      headers: { "Content-Type": "application/json" }
    })
    .then(response =>
      dispatch({
        type: ADD_EMPLOYEE,
        payload: response.data.employeeData
      })
    )
    .catch(err => console.log(err));
};

And here is my reducer

case ADD_EMPLOYEE:
  return {
    ...state,
    employees: [action.payload, ...state.employees],
    loading: false
  };

Everything works fine. The problem is the way it is stored in the database which is like this

{
  "employeeData": {
    "name": "Manpreet Sandhu",
    "title": "bootstrap 4",
    "funFact": "cccZCZCZ",
    "image": "CZCZCZC",
    "employeeId": "ZCZCZC",
    "dateOfJoining": "C"
  },
  "headers": {
    "Content-Type": "application/json"
  },
  "id": 7
}

I want to remove "employeeData" added before each entry.

This is what i receive in my action


回答1:


Refer to axios document,

  • axios.post(url[, data[, config]])

in your action thunk,

//...
axios
    .post("http://localhost:3004/employees", {
      employeeData,
      headers: { "Content-Type": "application/json" }
    })
//...

you have put the headers: { "Content-Type": "application/json" } in the data argument

I guess, what you would do, should be something like this

//...
axios
  .post("http://localhost:3004/employees",
    employeeData, //data
    { headers: { "Content-Type": "application/json" } } //config
  )

// or
axios({
  method: 'post',
  url: 'http://localhost:3004/employees',
  data: employeeData,
  headers: { "Content-Type": "application/json" }
})
//...


来源:https://stackoverflow.com/questions/50789122/react-redux-not-saving-in-state-as-intended

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!