Unable to update reducer state in redux

僤鯓⒐⒋嵵緔 提交于 2019-12-13 03:49:19

问题


I have a redux app which enables users to post something(like a blog post which contains only a title and body).The user can edit the post whenever they want to.I am not able to update the reducer,i.e. I just want to update the title and the body for that particular "id". I am trying to update the state in my reducer as shown below:

case SUBMIT_POST:
        let id = action.payload.id;
      return {
          ...state,
          [id]: {
            ...state[id],
            title: action.payload.title,
            body: action.payload.body
          }
        };

My action-creator looks like this:

//Action creator for submitting edited post
export function submitEditedPost(id, values, callback) {
  const request = axios.put(`${API}/posts/${id}`, {values}, {headers});
    return dispatch => {
      return request.then((res) => {
        callback();
        console.log(res.data.values)
        dispatch({
          type:SUBMIT_POST,
          payload: res.data.values
        })
      })
    }
}

How to update the reducer with the new edited title and body for that particular post id?

EDIT 1:

I am calling the action creator in my form onSubmit() method as shown below:

       onSubmit(values) {
        const { id } = this.props.match.params;
        const formData = {};
     for (const field in this.refs) {
       formData[field] = this.refs[field].value;
     }
        formData.id = id;
       console.log('-->', formData);
        this.props.submitEditedPost(id, formData, () => {
        this.props.history.push('/');
    });
  }

EDIT 2: Screenshot of the action in reducer is shown below:

EDIT 3: My entire reducer:

import _ from 'lodash';
import { FETCH_POSTS, FETCH_POST, CREATE_POST, EDIT_POST, SUBMIT_POST } from '../actions/posts_action';

export default function(state = {posts: {} }, 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, ...(_.mapKeys(action.payload,'id'))}};

    case CREATE_POST:
      return {...state, [ action.payload.id]: action.payload};

    case EDIT_POST:
        return { ...state, [action.payload.id]: action.payload};

    case SUBMIT_POST:
    console.log(action.payload);
        let id = action.payload.id;
      return {
          ...state,
          [id]: {
            ...state[id],
            title: action.payload.title,
            body: action.payload.body
          }
        };

     default:
      return state;
  }

}

EDIT 4 : Screenshot of redux-dev-tools:

来源:https://stackoverflow.com/questions/48249466/unable-to-update-reducer-state-in-redux

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