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()
}
}