Search code examples
reactjsreduxroutesredux-reducersredux-actions

Reducer not receiving action in redux or trouble with the action being called


I'm working on a MERN Stack. The database is posting to the route correctly, but the reducer is not receiving the action when trying to read all the database entries. It's possible that the action readAllEmployment() is not being hit by the front end correctly, but the information does render in PostMan.

index.js

import React, { useEffect } from 'react'
import { connect } from 'react-redux'
import { Carousel } from '../../components'
import { readAllEmployment } from '../../actions'
import './_resumeRender.scss'

const ResumeRender = () => {
useEffect(() => {
    console.log('Hit Use Effect')
    readAllEmployment()
  }, [])
return <></>
}

const mapStateToProps = (state) => ({
  resumeEmploymentReducer: state.resumeEmploymentReducer,
})

export default connect(mapStateToProps)(ResumeRender)

route.js

// load Model
const employmentModel = require('../models/employmentModel')

// @Route   GET api/employment/
// @Desc    Read All Employment
// @Action  readAllEmployment()
// @Access  Private
router.get('/', async (req, res) => {
  console.log('readAllEmployment Route')
  try {
    const employment = await employmentModel.find().sort('endDate')
    if (employment.length <= 0) {
      return res.status(400).json({
        errors: [{ msg: 'No employment was found' }],
      })
    }

    return res.json(employment)
  } catch (err) {
    console.error(err.message)
    return res.status(500).send('Server Error')
  }
})

reducer.js

import {
  GET_ALL_EMPLOYMENT,
  GET_ONE_EMPLOYMENT,
  DELETE_EMPLOYMENT,
  RESET_EMPLOYMENT,
  EMPLOYMENT_LOADING,
  EMPLOYMENT_FAIL,
  EMPLOYMENT_SUCCESS,
} from '../actions'

const resumeEmploymentReducer = (
  state = {
    allEmployment: [], // Pulls in all employment
    employment: null, // Pulls in Specific employment
    loading: false, // Has everything need been loaded
    success: {},
    error: {},
  },
  action,
) => {
  const { type, payload } = action
  switch (type) {
    case GET_ALL_EMPLOYMENT:
      console.log('GET_ALL_EMPLOYMENT Reducer')
      return {
        ...state,
        allEmployment: payload,
        loading: false,
      }
    case GET_ONE_EMPLOYMENT:
      return {
        ...state,
        employment: payload,
        loading: false,
      }
    case DELETE_EMPLOYMENT:
      return {
        ...state,
        allEmployment: payload,
        loading: false,
      }
    case RESET_EMPLOYMENT:
      return {
        ...state,
        employment: null,
        loading: false,
      }
    case EMPLOYMENT_LOADING:
      return {
        ...state,
        loading: true,
        employment: null,
        error: {},
      }
    case EMPLOYMENT_FAIL:
      return {
        ...state,
        error: payload,
        allEmployment: [],
        employment: null,
        loading: false,
      }
    case EMPLOYMENT_SUCCESS:
      return {
        ...state,
        success: payload,
      }
    default:
      return state
  }
}

export default resumeEmploymentReducer

action.js

export const GET_ALL_EMPLOYMENT = 'GET_ALL_EMPLOYMENT'
export const GET_ONE_EMPLOYMENT = 'GET_ONE_EMPLOYMENT'
export const DELETE_EMPLOYMENT = 'ELETE_EMPLOYMENT'
export const RESET_EMPLOYMENT = 'RESET_EMPLOYMENT'
export const EMPLOYMENT_LOADING = 'EMPLOYMENT_LOADING '
export const EMPLOYMENT_FAIL = 'EMPLOYMENT_FAIL'
export const EMPLOYMENT_SUCCESS = 'EMPLOYMENT_SUCCESS'

// @Route   GET api/employment
// @Desc    Read All Employment
// @Action  readAllEmployment()
// @Access  Private
export const readAllEmployment = () => async (dispatch) => {
  console.log('readAllEmployment Action')
  try {
    const res = await axios.get('/api/employment/')
    dispatch({
      type: GET_ALL_EMPLOYMENT,
      payload: res.data,
    })
  } catch (err) {
    if (err.response.data.errors) {
      dispatch({
        payload: { msg: err.response.statusText, status: err.response.status },
      })
    }

    dispatch({
      type: EMPLOYMENT_FAIL,
      payload: { msg: err.response.statusText, status: err.response.status },
    })
  }
}

Redux DevTools

resumeEmploymenrReducer
  allEmployment: []
  employment: null
  loading: false
  success: { }
  error: { }

console

Hit Use Effect

terminal

[1] Compiled successfully!
[0] Server is running on port 6060
[0] Database connected!
[0] readAllEmployment Route

PostMan

GET: http://localhost:6060/api/employment/

BODY RETURNS
[
    {
        "_id": "614b517cbc3fdc6d0d82ec4d",
        "title": "Job Title",
        "employmentType": "Full-Time",
        "company": "Compnay Name",
        "locationCity": "City",
        "locationState": "State",
        "startDate": "01-01-2021",
        "endDate": "01-01-2021",
        "description": "Description",
        "__v": 0
    }
]

Solution

  • I think you might need to utilize useDispatch from react-redux library.

    import { useDispatch } from 'react-redux';
    import { readAllEmployment } from '../../actions';
    
    const ResumeRender = () => {
      const dispatch = useDispatch()
    
      useEffect(() => {
        console.log('Hit Use Effect')
        dispatch(readAllEmployment())
      }, [])
    
      return <></>
    }
    
    export default ResumeRender