0
votes

so I have a dispatch to fetch from an api, which will then dispatch a success or error action based on the request's response code. On success my action should add to an array in my redux store, and on error it should just do nothing and return the current state. However for some reason when there is an error in the fetch request, the error action does get called (I have checked with redux devtools) BUT the action behaves as though the success action was called, so the array is updated with a new value even though there was an error. Any idea what could be going wrong?

Thank you

My actions:

export const ADD_PROJECT_SUCCESS = "ADD_PROJECT_SUCCESS"
export const ADD_PROJECT_ERROR = "ADD_PROJECT_ERROR"

export function addProject( project, projects ) {
    const url = 'project/'
    let tempProjects = projects
    tempProjects.push( project )
    const requestOptions = {
      method: 'POST',
      credentials: 'include',
      body: JSON.stringify( project )
    };
    return (dispatch) => {
      return fetchReq( requestOptions, url ).then( ([response] ) => {
        if( response.status === 201) {
          dispatch( addProjectSuccess(tempProjects) )
        } else {
          dispatch( addProjectError() )
        }
      })
    }   
 }

function addProjectSuccess( projects ) {
    return { type: ADD_PROJECT_SUCCESS, projects }
}

function addProjectError( ) {
    return { type: ADD_PROJECT_ERROR }
}

My reducer:

import { 
    ADD_PROJECT_SUCCESS, 
    ADD_PROJECT_ERROR, 
} from './projectActions'

const initialState = {
    projects: [],
}

export default function projectReducer( state = initialState, action ) {
  switch( action.type ) {
    case ADD_PROJECT_SUCCESS:
      return Object.assign( {}, state, { projects: action.projects } )
    case ADD_PROJECT_ERROR:
      return state
      } )
    default:
      return state
  }
}

My dispatches (dispatch functions were used in a functional component using mapdispatchtoprops):

  async function handleSubmit() {
    if( isValidForm() ) {

      let project = {
        "name": name,
        "description": description,
        "category": "default",
        "classification": classification,
        "collaborators": collaborators
      }
      await props.addProject( project, props.projects )
      props.hideForm()
    }
  }
1

1 Answers

5
votes

I just looked your code and it contains a bit issue.

let tempProjects = projects
tempProjects.push( project )

This is not good solution. You can do like this

const tempProjects = [...projects]
tempProjects.push(project);

Previously your code was trying to access to props variable. Look

await props.addProject( project, props.projects )
export function addProject( project, projects ) {

I think, this is the reason of weird case of your project and the other code snippets look good.

Hope this help you to understand and if you have any questions add comments below.