Having trouble establishing a connection between the Action and Reducer, as an error message pops up saying: "Promise not caught. Type Error: Dispatch function not

Hey pals, I'm facing an issue with the connection between Action and Reducer while attempting to send data fetched from the API. I keep getting a dispatch, not a function error and when I try to console.log(action.type), I see @@redux/INITw.y.u.w.s.a. Any help would be greatly appreciated. Thanks a ton!

Store

import { createStore, applyMiddleware , compose } from 'redux'
import reduxThunk from 'redux-thunk';
import combineReducers from './Reducers/index';

const enhancer = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
let store = createStore(combineReducers,enhancer(applyMiddleware(reduxThunk)))

export default store;

Action

import { READ_USER_DATA } from './../Types';

export const fetchUser = () => {
    return (dispatch) => {
        fetch(`https://jsonplaceholder.typicode.com/users`).then(response => response.json()).then(data => {
            dispatch({
                type: READ_USER_DATA,
                data: data
            })
        })
    }
}

Reducer

import { READ_USER_DATA } from './../Types';

const userReducer = (state = {}, action) => {
    switch (action.type) {
        case READ_USER_DATA:
            return { ...state,userInfo: action.data  }
        default:
            return state;
    }
}

export default userReducer;

combine Reducers

import { combineReducers } from "redux";
import userReducer from './UserReducer';

export default combineReducers({
    user: userReducer,
})

connect - Code in component-

export default connect((state) => {
    console.log(state)
    return {
        userInfo: state.user.userInfo
    }
},{ fetchUser })(Home)

Answer №1

When using the useEffect hook, my code looks like this:

 useEffect(() => { fetchUser() }, [])

An important thing to note is that curly braces {} should be used instead of parentheses () in your useEffect. Additionally, when utilizing the legacy connect function, you must call props.fetchUser instead of just fetchUser directly.

A more refined approach would resemble the following:

useEffect(() => { props.fetchUser() }, [])

Alternatively, it could be even better done like:

const userInfo = useSelector(state => state.user.userInfo)
const dispatch = useDispatch()
useEffect(() => { dispatch(fetchUser()) }, [])

By following this method without relying on the connect function at all.

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

Change the right border style for the second and third ToggleButtons in the ToggleButtonGroup

I've been working on this for a few hours now and I can't seem to get it right. Currently, I'm using Mui v5 and trying to style the ToggleButtons to look like regular MUI buttons. So far, I was able to achieve this transformation: https:/ ...

Generate an array that can be accessed across all components

As someone new to reactjs, I'm trying to figure out how to handle an array of objects so that it can be global and accessed from multiple components. Should I create another class and import it for this purpose? In Angular, I would typically create a ...

What is causing styled-components to include my attributes in the DOM?

In various parts of my code, there is a snippet like this: import React from 'react' import styled from 'styled-components' type PropsType = { direction?: 'horizontal' | 'vertical' flex?: number | string width ...

Is there a way to extract a token from the URL in a Nextjs/React application?

I am currently developing a project that relies heavily on API integration. My front-end interface is built using React and Next.js, while the back-end API is developed with Laravel. Within my front-end page, I have implemented a token in the URL to help ...

Coordinating a series of maneuvers

When it comes to coordinating multiple sequential actions in Redux, I find it a bit confusing. I have an application with a summary panel on the left and a CRUD panel on the right. My goal is to have the app automatically update the summary after a CRUD op ...

What is the function of async in Next.js when triggered by an onClick

Need help with calling an async function pushData() from a button onClick event async function pushData() { alert("wee"); console.log("pushing data"); try { await query(` //SQL CODE `); console.log("Done&quo ...

Exploring the latest updates in MUI modern version

The MUI documentation suggests using a modern folder with components designed for modern browsers. Is there a way to configure webpack to automatically rewrite imports like import {Box} from "@mui/material" to use the modern version without manually changi ...

When invoking a function, a React Component utilizes the props from the first element instead of its own

Whenever I try to invoke a function of a component, it seems to be replacing the parameters and passing the props of the first array element instead of the selected one. To illustrate this issue, let's take a look at some code: Firstly, here is how ...

The getSession provided by the getSession function is accessible within getServerSideProps but appears as undefined within the component

Whenever I try to log the session variable inside the Dashboard component, it comes back as undefined. However, when I log it inside the getServerSideProps function, it returns the correct details. Am I missing something here? Objective: My goal is to fet ...

The final version of the React App is devoid of any content, displaying only a blank page

As a beginner in learning React, I must apologize for any basic issues I may encounter. I recently created a shoe store App (following this helpful tutorial on React Router v6) Everything seems to be working perfectly in the development build of my app. ...

Unlocking the contents of an array from a separate file in Next.js

I am developing a Quiz App that consists of two main pages: takeQuiz.js and result.js. My goal is to transfer the data from the multiple-choice questions (mcqs) in takeQuiz.js to be accessible in result.js. Utilizing router.replace(), I ensure that once th ...

The value entered for creating a payment method is invalid: the card must be in the form of an object

I am in the process of setting up a payment method using the Next.js library from Stripe. Here is the code snippet: import React, { FunctionComponent } from 'react'; import type { DisplaySettingsProps } from '@company/frontoffice/types' ...

Electronic circuit embedded within a material-textured text field offering multiline functionality

While experimenting with TagsInput, I came across this helpful snippet on codesandbox that you can check out here. The challenge I encountered is when there are numerous chips, they extend beyond the boundaries of the text field. My goal is to implement ...

Ways to transmit information from a React application to a Node server

As a Nodejs beginner, I am using the rtsp-relay library for live streaming. Currently, it is working in the frontend when the URL is included in the server proxy object like this: rtsp://.....@..../Stream/Channel/10. However, I want users to be able to inp ...

Here's a guide on customizing the appearance of the date picker in NativeBase components for React Native by

Is there a way to show icons while using the date picker component from the Native Base UI library? ...

Why is my React app opening in Google Chrome instead of the API?

I have a link in my React app that is supposed to open a PDF in another page, but for some reason Google Chrome is redirecting me to the React application instead of opening the API endpoint that renders the PDF. The URL for the PDF is /api/file/:_id and m ...

What is the best way to implement the Snackbar functionality within a class-based component?

My snackbar codes are not working as expected when I click the "confirm" button. I want the snackbar to appear after clicking the button. Most examples I've seen use functional components, so how can I get the Snackbar to work properly in a class comp ...

Add the file retrieved from Firestore to an array using JavaScript

Trying to push an array retrieved from firestore, but encountering issues where the array appears undefined. Here is the code snippet in question: const temp = []; const reference = firestore.collection("users").doc(user?.uid); firestore .collec ...

How to access the onchange text in a react-select search component

I'm currently working on implementing search select functionality in my webpage using the react-select-search npm package. This is my main component: import React, { Component } from "react"; import Task from "./task"; // Rest of ...

What is the best way to dismiss the modal window in React upon clicking the "Add product" button?

Hello all, I'm having trouble figuring out how to close the modal window in React. I want it so that when the user clicks on the "Add" button, a modal window opens for data input, and then upon clicking the "Add product" button, the window closes imme ...