React and Redux error: Attempting to access properties of an undefined variable ('type')

While developing a redux reducer that manages user login and logout, I encountered an issue with the logout functionality. The login process is functioning properly, but upon attempting to logout, I received the following error:

loginReducer.js:60 Uncaught TypeError: Cannot read properties of undefined (reading 'type')
    at loginAPIReducer

This is how my current code is structured:

//logouttypes:

export const LOGOUT_REQUEST = "LOGOUT_REQUEST";
export const LOGOUT_SUCCESS = "LOGOUT_SUCCESS";
export const LOGOUT_FAILURE = "LOGOUT_FAILURE";

//logoutactions:

import {LOGOUT_REQUEST, LOGOUT_SUCCESS, LOGOUT_FAILURE } from './logoutTypes'


export const logoutRequest = () => {
  return{
    type: LOGOUT_REQUEST
  }
}

export const logoutSucces = response => {
  return{
    type: LOGOUT_SUCCESS,
    payload: response
  }
}

export const logoutFailure = error => {
  return{
    type: LOGOUT_FAILURE,
    payload: error
  }
}

// reducer:

export const startLogout = () =>{
  
  
  return dispatch => { 

    dispatch(logoutRequest)
    .then(res => {
      dispatch(logoutSucces)
    })
    .catch(error => {
      dispatch(logoutFailure(error))
    })
  }
}




const loginAPIReducer = (state = initialLoginState, action) => {
  console.log(action.type)
  switch(action.type){
    case LOGIN_REQUEST:
      return{
        ...state,
        loading: true
      }
    case LOGIN_SUCCESS:
      return{
        loading: false,
        user: action.payload,
        error: '',
        logedIn: true
      }
    case LOGIN_FAILURE:
      return{
        loading: false,
        user: '',
        logedIn: false,
        error: action.payload
      }
    case LOGOUT_REQUEST:
      return{
        ...state,
        loading: true
      }
    case LOGOUT_SUCCESS:
      return{
        loading: false,
        user: '',
        logedIn: false,
        error: ''
      }
    case LOGOUT_FAILURE:
      return{
        loading: false,
        error: action.payload
      }
    default:
      return state;
  }
}

export default loginAPIReducer;

The startLogout function is triggered in the navigation bar:

<Button variant="outline-success" onClick={startLogout}>Log out</Button>

The reducer is properly connected to the store. It's puzzling that the login functionality works without issues while the corresponding logout feature encounters errors as mentioned above.

Your assistance is greatly appreciated!

Answer №1

Ensure that you include the type parameter in your actions when passing them to the reducer, as indicated by the error message stating property type is not defined.

export const startLogout = () => {
  
  
  return dispatch => {

    dispatch(logoutRequest()) // passes: { type: LOGOUT_REQUEST }
    .then(res => {
      dispatch(logoutSuccess(res))
    })
    .catch(error => {
      dispatch(logoutFailure(error))
    })
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error: The variable 'path' has not been declared in the context of Express

Whenever I click a link on the page, even though it renders properly, an error occurs. ReferenceError: path is not defined at app.get (/var/www/example.com/example-domain/server.js:106:19) at Layer.handle [as handle_request] (/var/www/example.com/example- ...

Adding map markers from a JSON feed to your React Google Map - a step-by-step guide!

I'm currently working on a React project that involves integrating Google Maps: const MarkerComponent = ({text}) => <div>{text}</div>; export default class NavMap extends Component { constructor(props) { super(props); this.s ...

How can one effectively extract data from a database in a React application?

We have a basic react app with authorization, utilizing JWT tokens and Redux for state management. Personally, I find the code quite complex and obfuscated, making it challenging to grasp fully. However, let's set that aside. Upon login, a token is s ...

Guide on creating 2 select inputs with distinct elements?

Imagine you have two select inputs called 'Favorite Fruits' and 'Least Favorite Fruits'. Both of them contain a list of 5 fruits. // The following code is an example to demonstrate the issue <select name='favoriteFruits'& ...

Integrating Javascript and JQuery in Reactjs: A Comprehensive Guide

Currently, I am working with ReactJS and utilizing the Next.js framework. My goal is to implement the provided code snippet in index.js to display data (day, month, etc.). How should I go about achieving this? Here is the code snippet: <script> fun ...

After deploying to Firebase hosting, the next/image component is not showing any images

While my images load and display correctly on npm run dev, they do not show up after deploying my project. I have been using next/image to upload the images, storing them in an Assets folder with a format of src='/Assets/car.jpg'. How can I res ...

React App not functioning properly with http-proxy-middleware

After setting up proxies on my create-react-app application with http-proxy-middleware, I'm encountering a persistent 404 error whenever I click the relevant link. Following the setup instructions meticulously, I still can't seem to resolve this ...

Changing the Position of HTML Scripts in React

I am facing an issue where I need to relocate an external script within a specific section of my page. However, I am unable to access the CSS attributes associated with this item. It seems that it is displayed as an iFrame, making it difficult to modify th ...

Using the same conditional statement on multiple pages within a Next.js application

I'm currently working on a project with Next.js and I've encountered an issue when fetching data from my server using the useSWR hook. There are certain conditions that need to be met in order to display specific content on the page, as shown in ...

The value is not getting set after calling React Hook UseState

I am currently working on a React component that handles payment processing. There is a part of my code where I utilize the useEffect hook alongside useState to set certain values. Check out the code snippet below: React.useEffect(()=>{ axiosFetch ...

Troubleshooting problem with CRUD operations in MySQL, Express, React.js, and Node.js

Is there a way to post data from three input fields in a form to a MySQL database table using Axios? I have attempted multiple times but have been unsuccessful. Can someone provide the code for connecting to the database and inserting the query? //PostFo ...

The success message is not being displayed after clicking the pay button using ReactJS, Stripe Payments, Node, and

Currently, I am working with ReactJS, Node.js, and Express while integrating the Stripe Payment API. However, I am facing an issue where after clicking the pay button and entering the dummy credit card details, the payment processing does not proceed as ex ...

React Class Component with Dark Mode功能

Having an issue with toggling between dark and light mode on the navbar using a toggle switch. Whenever I click on the switch, I encounter the following error: Error: Cannot read properties of undefined (reading 'state') This error is related t ...

Cross-origin resource sharing (CORS) issue encountered while trying to play an mp

I am facing an issue with my React application where it is unable to play audio from a different source due to a CORS error. Example: Interestingly, when I visit https://www.w3schools.com/tags/tag_audio.asp, input the above URL and click play, it works fi ...

Struggling to Enforce Restricted Imports in TypeScript Project Even After Setting baseUrl and resolve Configuration

I am facing challenges enforcing restricted imports in my TypeScript project using ESLint. The configuration seems to be causing issues for me. I have configured the baseUrl in my tsconfig.json file as "src" and attempted to use modules in my ESLint setup ...

What are the steps to fix a timeout error with React.js and socket.io acknowledgements?

My setup includes a Node.js server and a React.js client application. Data is exchanged between them using socket.io, but I'm running into an issue with implementing acknowledgment. Whenever I try to implement acknowledgment, I receive a timeout error ...

What is the best way to make the first option blank?

Is there a way to have the select field start with an empty value instead of the default dollar sign? The demonstration can be found at https://codesandbox.io/s/material-demo-forked-xlcji. Your assistance in achieving this customization would be greatly a ...

Exploring Iteration of TypeScript Arrays in ReactJS

Issue Encountered: An error occurred stating that 'void' cannot be assigned to type 'ReactNode'.ts(2322) The error is originating from index.d.ts(1354, 9) where the expected type is related to the property 'children' defi ...

What's the trick to ensuring that state is set with useEffect() every time the page is refreshed?

Hey there! I've got some code that's pretty straightforward and not too complicated, so please take a moment to read through it. (I'm using React with Next.js) First off, in the root file app.js, there's a useEffect function that fetch ...

Exploring ways to customize the input color of Material UI TextField when it is disabled [Version: 5.0.8]

I am having trouble changing the border color and text color when an input is disabled. I have tried multiple variations, as seen below: const textFieldStyle = { '& label': { color: darkMode?'#1976d2':'', } ...