Redux actions do not cooperate with functions, preferring to be implemented inline instead

I am a beginner in Redux and JavaScript and just came across this issue,

When I use the line

dispatch({type: 'REQUEST_START'});
it works fine, but when I write it like this:

dispatch(requestStart);

No actions are being fired!

Any suggestions on why this might be happening? It's strange because it works in another app that I have.

This is the code I am working with:

import { booksActionTypes } from './books.types';

export const requestStart = () => ({
    type: booksActionTypes.REQUEST_START,
});

export const requestSuccess = books => ({
    type: booksActionTypes.REQUEST_SUCCESS,
    payload: books,
});

export const requestFailure = errMsg => ({
    type: booksActionTypes.REQUEST_FAILURE,
    payload: errMsg,
});

export const actionCreators = {
    // "applicationUrl": "http://localhost:51374", http://erikswed.ddns.net:8965/api/BooksXml/getbooks/fromall/?title=dep&author=&genre=&price=
    // "sslPort": 44378
    requestBooks: (book) => async (dispatch, getState) => {
      dispatch({type: 'REQUEST_START'});
      var queryString = Object.keys(book)
        .map((key) => {
          return encodeURIComponent(key) + "=" + encodeURIComponent(book[key]);
        })
        .join("&");
      var url = "http://erikswed.ddns.net:8965/api/BooksXml/getbooks/fromall/?" + queryString;
  
      console.log(`url: `, url);
      await fetch(url)
        .then((res) => res.json())
        .then((booksList) => {
          dispatch(requestSuccess, booksList);
        })
        .catch((rejected) => {
          console.log(rejected);
          dispatch(requestFailure, rejected);
        });
  
      // const response = await fetch(url);
      // const booksList = await response.json();
    },
};

Answer №1

requestStart is a function that returns an object, so remember to call it like this - dispatch(requestStart())

Alternatively, you can define it as an object and directly use it without needing to call it.

export const requestStart = {
    type: booksActionTypes.REQUEST_START,
};
...
dispatch(requestStart)

Using a function as an action creator allows you to pass arguments to add to the action object. It's recommended to keep using the function approach but ensure consistency by calling it when needed.

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

Exploring the potential of Framework7 in Single Page Applications: optimizing performance by preloading

I'm currently working on developing a web application using Framework7. Framework7 offers routing APIs for navigating between HTML pages. It seems that the pages are loaded dynamically through AJAX requests. I am curious if it is possible to preload ...

Use jQuery to parse the JSON below and then showcase the information in an HTML table

Can anyone assist me with parsing the following JSON using jQuery and presenting it in an HTML table? I want to showcase the values of "key" and "doc_count" in an HTML table. Your help would be greatly appreciated. Please find the JSON data below: { ...

Encountered an issue while attempting to load the required module

I'm having trouble setting up Stripe for my app and getting errors when trying to implement the module. Typically, I would require the module at the top of the file in order to use it, but when I do this in the paymentCtrl file, it doesn't work a ...

How to send a DOM element's value to an AJAX request using HTML.PagedList parameters

As I delve into learning ajax requests, I find myself questioning if I am on the right track. Currently, I have a page that incorporates pagination, sorting, and searching functionalities. My goal is to implement these features using ajax to avoid reloadin ...

SweetAlert will only render if it is not hidden

One of the components in my codebase utilizes SweetAlert from "react-bootstrap-sweetalert". The issue I am facing is that even when the "show" property is set to false, SweetAlert is still being rendered and the function inside it gets called regardless o ...

I can't seem to retrieve any values from the API other than "chicken"

Is there a way to make the search bar in my recipe app look for recipes that I provide, rather than fetching data from useState? Any suggestions on how I can achieve this? import React, { useEffect, useState } from 'react'; import Recipe from &ap ...

Incorporating the Microsoft Teams Embedded Share Button within a React-based web application

Recently, I successfully implemented the Microsoft Teams Embedded Share Button in React by following these steps: Step 1: First, I included the launcher.js script on my web app: I simply added this script to a useEffect hook: <script async defer src=& ...

I have experimented with both POST and GET methods in Node.js, exploring a variety

After creating a login page with a GET form, the server code includes: app.use(express.static(path.join(__dirname, 'public'))); I am facing an issue trying to implement a POST request. When I use "POST", it gives me a "CANNOT / PO ...

What is the best way to reset the size of an element in webkit back to its original dimensions?

I am having an issue with an element that changes to display absolute and covers its parent element on focus via javascript. However, when it goes back to its default state on blur, it does not return to its original position. This problem seems to only o ...

Having trouble incorporating an API module into a nested component in Vue

I have encountered a perplexing issue when attempting to import an API module into a nested component within a Vue application. After simplifying the problem as much as possible, I created a codesandbox example to demonstrate it. The problem arises when ...

Using JavaScript to modify the -webkit-animation-play-state

Hello, I'm currently facing a challenge in changing my css3 -webkit-animation-play-state property from paused to running upon clicking on another div. Does anyone have any suggestions on how I can achieve this? I believe JavaScript might be the way to ...

Is it unorthodox to utilize constructor instances as prototypes in "WebGL - Up and Running"?

In the book "WebGL - Up and Running," a unique custom geometry is created in a rather straightforward manner. However, what caught my attention was the penultimate line of code. Here's how it looked: Saturn.Rings = function ( innerRadius, outerRadius ...

Can you please specify the type of values being entered as input?

Query: How do I identify the data type of the value entered in an input field? Whenever I use typeof, it always returns string unless the string is empty. I searched various forums extensively but couldn't find a solution. Can someone assist me with t ...

Securely package tailor-made services within an application

Recently, I have been researching how to create custom services for AngularJS. However, all the examples I found demonstrate defining the service directly on my app using myApp.factory(...). For reference, you can check out the official docs for an example ...

"Implementing a seamless transition effect on two slideshows using jQuery's fadeslideshow

I currently have a homepage featuring a fadeslideshow with 5 slides. The fadeslideshow plugin being used can be found at http://plugins.jquery.com/project/fadeslideshow. On the homepage, there is also a menu bar with various menu items. When a user clicks ...

Using percentages to position Div elements

Currently, I am working on an HTML page that requires a div element spanning the full width of the page. My goal is to arrange other divs within this full-width div using percentages rather than pixels. The class associated with this div is .question. Thi ...

Share the Angular library distribution folder on a new git repository

I am faced with a dilemma regarding my Angular library that I often use in another project. The way I build my library is by running the command: ng build Upon executing this command, a dist/my-library directory is created at the library root. My goal is ...

Combine values within a single property of an object using the reduce method

My array consists of objects structured like this: let array = [{ "Age": 20, "Name": "Kevin" }, { "Age": 15, "Name": "Alfred" }, { "Age": 30, "Name": "Joe" }]; I am aiming to transform it into an object with combined values like t ...

What is the correct way to change the v-model value of a child component within a parent component

Currently, I am in the process of mastering Vue.js and I have a specific goal. I want to modify the binding value of the child component's v-model and then trigger an event in the parent component. As I delve into the Element UI documentation, I aim ...

Creating an alert pop-up that displays text based on the prompt input type: A step-by-step guide

I'm a new to Javascript and I'm trying out some basic scripts. My objective is to display a prompt message (1.) asking for a name, then show an alert (2.) based on the input from the prompt. If the input is a valid name (a string), then the alert ...