What is the process for linking read-only methods to Redux object instances?

Let's say I have a "user" object stored in redux, with fields for first name and last name (

interface User { firstName : string, lastName : string}
if using typescript). After retrieving a user from redux, I want to obtain the full name of the user by combining the first and last names:
${user.firstName} ${user.lastName}
. Currently, I have a function:

function getFullName(user: User) : string { 
  return `${user.firstName} ${user.lastName}`
}

In my application, I have several similar read-only functions like this one. I would prefer to have a method that can be called as user.getFullName() or even user.fullName. This way, I wouldn't need to import multiple functions separately or distinguish between properties and functions.

I could achieve this by creating class objects every time data is retrieved from redux and ensuring to use {...user} when saving back to redux to convert it into a plain JavaScript object. However, this approach would introduce additional boilerplate code, especially when using typescript in combination with redux.

This issue seems like something that should have a straightforward solution. Is there a simple and efficient way to tackle this problem?

Answer №1

Member methods within JS objects are treated in the same way as other properties. This means that you can define a member method getFullName() on the User interface and implement it within the initalUserState. The getFullName() method will persist even after the redux action is processed.

interface User {
    firstName: string; lastName: string;
    getFullName: () => string;
}

const initialState: User = {
    firstName: '',
    lastName: '',
    getFullName () {
        return `${this.firstName} ${this.lastName}`;
    },
}

const reducer: Reducer<User, Action> = (state = initialState, action): User => {
    // logic to handle actions
    return state;
}

The spread syntax

{ ...state, firstName: action.firstName }
will still function correctly without overwriting the getFullName() method.

Within a component, you can utilize the getFullName() method as demonstrated below

const Component1: FC<User> = (user) => <div>{user.getFullName()}</div>

export default connect<User, {}, {}, ApplicationState>
    (state => state.user, null)(Component1)

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

Display HTML components as JSON data using AngularJS

Recently, I started exploring angular js and faced a challenge in formatting json data with the help of angular js. Below is a snippet of my json data: [ {"field_add_link": "<a href=\"/drupal3/drupal3/\">Home</a>"}, {"field ...

What is the best way to find out if an array index is within a certain distance of another index?

I'm currently developing a circular carousel feature. With an array of n items, where n is greater than 6 in my current scenario, I need to identify all items within the array that are either less than or equal to 3 positions away from a specific inde ...

The mysterious case of TypeScript imports making all other code vanish

I have multiple classes located in root/app/providers/engine/engine.ts. In my test specification file spec/engine/engine-spec.ts (the spec/ directory is also where the jasmine support/ resides), I have a simple test: ///<reference path="../../typings/g ...

Combining NodeJS with PHP: A Seamless Integration

They say NodeJS is perfect for creating real-time chat applications and I'm eager to add a chat feature to my website. Right now, I have the design ready and need to work on the back-end code. However, when I use socket.io + express, things don' ...

The Mystery of Two Nearly Identical Functions: One function is queued using Queue.Jquery, but the effects fail to work on this particular function. What could be causing this

In short, I am currently working on my first portfolio where I am utilizing Jquery to manipulate text. My goal is to have the text fade in and out sequentially. However, when using the queue function to load another function, the text within the span tag ...

Sign up for our Joomla website by completing the registration form and agreeing to our terms and conditions

I am currently working with Joomla 1.5 and I need to incorporate a checkbox for users to agree to the terms and conditions. I attempted to use the code below, but it is not functioning as expected. Even when the checkbox is ticked, it still triggers an a ...

Reload the page when the value reaches 1

Hello, I am currently working on creating a system where my index page refreshes when a value in my database is set to 1. However, I am having trouble with the code as only my index.php is not refreshing. index.php <script> interval_timer = setInt ...

Sending an array as JSON data to PHP using the $.ajax post method. The $_POST array is

After spending a considerable amount of time on this, I'm still struggling to figure out what I'm doing wrong. I'm having difficulty retrieving the data in the PHP file. I've made multiple calls to "copy" to populate the "result" arr ...

The required property '0' is not found in the type 'any[]' but it is needed in the type '[{ post_id: string; title: string; }]'

I have gone through this post but I am still struggling to understand the issue. Why am I unable to pass this array to the update call? // create a new object with updated post properties const newPost = await this.postRepository.create(data); await thi ...

Puppeteer App Error: An error has been detected on the client side

I am facing an issue using Puppeteer with NEXT.JS while attempting to capture a screenshot. Everything runs smoothly on localhost, but in production, the captured image comes back with the following error message: Application error - a client-side exceptio ...

What is the best way to trigger b-tab based on a specific condition?

Hey there, I'm just starting out with Vue3 and I have a bit of a challenge. I've got an SVG image with different parts, a data variable that changes when a particular part of the image is clicked, and some tabs (b-tabs). Is it possible to automat ...

Increasing the token size in the Metaplex Auction House CLI for selling items

Utilizing the Metaplex Auction House CLI (ah-cli) latest version (commit 472973f2437ecd9cd0e730254ecdbd1e8fbbd953 from May 27 12:54:11 2022) has posed a limitation where it only allows the use of --token-size 1 and does not permit the creation of auction s ...

Tips for directing your attention to an input field in Angular

I'm struggling to find a simple solution for setting focus programmatically in Angular. The closest answer I found on Stack Overflow is about dynamically created FormControl, but it seems more complex than what I need. My situation is straightforward ...

How can I make a recently added row clickable in an HTML table?

I have a table where each row is given the class ".clickablerow". I've set up an onclick function so that when a row is clicked, a dialog box appears allowing me to insert text above or below as a new row. The issue I'm facing is that even though ...

Exploring the Possibilities of WebAudio API through Asynchronous Events

Is there a way to trigger events after an oscillator finishes playing using the webaudio API? I am attempting to update my Vue component reactively to display data in the DOM while a note is being played. Here's a snippet of my code: <template> ...

Having T extend Record<string, any>, the keyof T does not return 'string' as a type

My goal is to achieve the following: type UserDataProps<FieldName extends keyof DataShape, DataShape extends Record<string, any>> = { id: string; value: DataShape[FieldName]; } const userDataBuilder = <FieldName extends keyof DataShape, ...

Visualization of extensive datasets in JavaScript

I'm currently developing a dashboard in JS for displaying sales data plots to users. Can anyone recommend a JavaScript library that meets the following criteria: Capable of plotting a large number of points (ex: 100k or more) Interactive functional ...

Utilize Three.js to Add Depth to 2D Images with Extrusion

After searching online, I have been unable to find a method to extrude a colored image in Three.js. My goal is to create a design similar to a Minecraft item where the image is used to generate an extruded geometry. An example of what I'm trying to ac ...

AngularJS: Default value causes dropdown menu text to not display

I am facing an issue with my select menu. <select id="dd" ng-show='data != null' ng-model='search'></select> Initially, I set the filter to display only USA by default. $scope.search = 'United States of America' ...

Transforming a class component into a functional component using React for a session

While working on a React application, I encountered the need for auto logout functionality for inactive users. After referring to this resource, I attempted to convert my class component code to functional components. However, I faced issues as the functio ...