Retrieve the current state within a redux action

Many experts recommend consolidating the logic in action creators to streamline the reducer's logic.

Picture a basic (normalized) state:

const initialState = {
  parent: {
    allIds: [0],
    byId: {
      0: {
        parentProperty: `I'm the parent`,
        children: [1, 2]
      }
    }
  },
  children: {
    allIds: [1, 2],
    byId: {
      1: {
        childrenProperty: `I'm the children`
      },
      2: {
        childrenProperty: `I'm the children`
      }
    }
  }
}

If I were to delete the parent, I would also need to delete the associated children.

An example of an action creator for this scenario:

function removeParent(parentId) {
  return {type: 'REMOVE_PARENT', payload: {parentId}};
}

and

function removeChild(childId) {
   return {type: 'REMOVE_CHILD', payload: {childId}};
}

Currently, my approach with redux-thunk looks like this:

function removeParentAndChildren(parentId) {
  return (dispatch, getState) {
    const childrenIds = getChildIds(getState(), parentId);
    const childActions = childrenIds.map(removeChild);
    const combinedAction = combineActions([
      removeParent(parentId),
      ...childActions
    ], 'REMOVE_PARENT_AND_CHILDREN');
    dispatch(combinedAction);
  }
}

This method allows me to bundle smaller actions into one larger action, keeping the reducer logic straightforward by simply removing keys from objects.

On the flip side, using redux-thunk just for retrieving state information is frowned upon as an anti-pattern.

How do you handle similar challenges? Could tools like redux-saga be beneficial in this context?

Answer №1

It appears that the issue you are facing is quite prevalent, especially in more complex applications. I recommend considering utilizing redux-orm, although it may be challenging to grasp initially and integrate into your project. However, once configured, it simplifies the process of managing relationships between entities.

Answer №2

In my opinion, a different approach is needed in this situation. My suggestion would be to remove the child while deleting the parent without dispatching the child_delete action. By creating a new state during the deletion of the parent in the reducer, you can also access and remove the children associated with that parent from the state.

If you still prefer to dispatch actions separately, you can pass child IDs from the component to the action. Then, within that action, you can dispatch two distinct actions - one for deleting the parent and another for deleting the children by their IDs.

----------- REVISION -------

// The current application's initial state
const initialState = {
  parent: {
    allIds: [0],
    byId: {
      0: {
        parentProperty: `I am the parent`,
        children: [1, 2]
      }
    }
  },
  children: {
    allIds: [1, 2],
    byId: {
      1: {
        childrenProperty: `I am a child`
      },
      2: {
        childrenProperty: `I am a child`
      }
    }
  }
}

export default function batchManagement(state = initialState, action) {
  switch (action.type) {
    case 'DELETE_PARENT':  //assuming action.deleteParents = [0]
      // Modify parents and children or create a completely new state here since you have access to the state
    case 'DELETE_CHILDREN':
      // Provide a new object for the state
    default:
      return state;
  }
}

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

What is the method for sending an axios post request using the application/x-www-form-urlencoded content type?

How can I successfully send an axios post request using application/x-www-form-urlencoded? I am trying to include a refresh token in the request, but currently an empty object is being sent. However, I have verified that the token exists when checking "us ...

I'm having trouble using Discord.js to set up a custom role with specialized permissions for muting users

module.exports = { name: "mute", description: "This command is used to mute members in a server", execute: async function (msg, arg) { const muteRole = await msg.guild.roles.cache.find((r) => r.name == "Mute ...

Blend express router by chaining the (.route) method with other HTTP methods like (.get, .post, etc) to create

Here is my code structure: let router = require( 'express' ).Router(); Later on, I define my routes like this: router .route( '/' ) .get( listMiddleware ); router .route( '/:id' ) .get( getOneByIdMiddleware ...

Modifying linked dropdown selections with jQuery

I'm trying to create a recurrent functionality where I have 3 select elements. When the first select is changed, it should update the second and third selects accordingly. If the second select is changed, then it should also affect the third select. ...

Sending information and HTML content from PHP to JavaScript using JSON

As a beginner to this, I acknowledge any noticeable mistakes. I am attempting to utilize an ajax call from Javascript to randomly select a movie from a database, generate some html containing information about the movie, and also return an array of inform ...

What is the best way to trigger the selection options in a dropdown menu with several buttons?

Is it possible to display the options from a select-option tag using a different button? I have either a div or another button. I want to be able to show the list of options from my select tag by clicking this button. Here is my select tag: <select&g ...

Obtain accurate dispatch type by leveraging ConnectedProps in conjunction with redux-thunk

Currently, I am utilizing Redux-Toolkit and Typescript. Specifically, my goal is to implement ConnectedProps as recommended in the redux documentation. However, it appears that the dispatch type is not recognized correctly (it is identified as a normal Dis ...

What is the best way to move the numerical range value into a span element?

How can I implement the "update" function to retrieve the current slider value and transfer it to a Meter element with the message "Value: [current value]". The indicator color should be #ffff00 if the current value is at least 85, otherwise, it should b ...

Adjust the CSS of a nested div within the currently selected div upon page load

I am facing an issue with a page that users access by clicking through an ebook. Upon clicking a link, they are directed to a specific product on the page, and the URLs look like example.com/#product1 example.com/#product6 example.com/#product15, etc... ...

"When trying to access a jQuery ID, it is coming back as undefined even though the

I'm attempting to obtain the ID of a specific element, save it as a variable, and then utilize that ID value to interact with other elements in the same section bearing the identical ID. <div class="mainContent"> <div class="articleContent"& ...

I encountered a PrimeVue error while running a Vue Jest test

When working on a Vue jest test, I encountered an error message "No PrimeVue Confirmation provided!" which seemed to be related to the useToast() and useConfirm() services. "transformIgnorePatterns": [ "<rootDir>/node_modules/(?! ...

Creating a horizontal scrolling section for mobile devices using CSS

Looking to create a horizontal scroll area specifically for mobile devices, similar to the design seen here: https://i.sstatic.net/oSNqL.png Additionally, I want to hide the scrollbar altogether. However, when attempting to implement this, there seem to ...

Enhance the attributes of a collection of objects using values from a different array

Looking for a way to enhance a set of objects with properties sourced from another array? I have two arrays at hand. The first one contains a series of objects, while the second one consists of integers. My goal is to attribute a new property to each objec ...

Changing the Material UI imported Icon on click - a step-by-step guide

Hey there, I'm currently working with React JS and Redux. I have a challenge where I need to change the star outline icon to a filled star icon on click. The icon is located just after emailRow in the emailRow__options section. Can someone assist me w ...

Tips for transferring information to a node server

Currently, I am working with Express and facing the challenge of dynamically sending data to the app.get() method. Specifically, on my index page, there is a list of topics, and upon clicking one, I need to send the name of that element as the required dat ...

Sending an array of objects to a MySQL database using React and NodeJS: A comprehensive guide

As someone who is new to NodeJS and Mysql databases, I am currently working on a small React project that involves a week calendar for booking lessons. My main focus right now is creating an admin panel where teachers can set their availability throughout ...

Click on each item within the v-for loop to gather relevant information, and subsequently iterate through the collected data

Within a v-for loop, I have implemented a button that, when clicked, retrieves specific data. The objective is to display this data below or in place of the clicked button. <div v-for="(item, index) in items" :key="index"> <button @click="fetch ...

The error "Cannot invoke the indexOf method on an undefined element at order" is being encountered in Javascript

Looking for assistance with creating a function to sort a string where each word contains a single number from 1 to 9 (no 0). For instance, given the input: "is2 Thi1s T4est 3a", the desired output should be "Thi1s is2 3a T4est". The current code snippet ...

The battle of efficiency: Generating content from JSON files compared to pulling from a

Greetings, fellow forum members! This is my inaugural post here. Despite the title possibly hinting at duplication, I have come across similar posts such as: one, two, three, four, and so on. However, my query bears a slight variation. I am currently in th ...

Navigating the implementation of undefined returned data in useQuery hook within Apollo and ReactJS

I am facing an issue with my code where the cookieData is rendered as undefined on the initial render and query, causing the query to fail authentication. Is there a way to ensure that the query waits for the response from the cookie API before running? co ...