I just created a slice inline function within my Redux Toolkit setup

Having issues with the following function:

    export const authSlice = createSlice({
  name: "auth",
  initialState: {
    credentials: {},
    isLoading: false,
  },
  reducers: {
    isLoading: (state) => {
      state.isLoading = !state.isLoading;
    },
  },
  extraReducers: (builder) => {
    builder
      .addCase(signInByEmail.fulfilled, (state, action) => {
        state.credentials = action.payload;
      })
      .addCase(signInByEmail.rejected, (state, action) => {
        Alert.alert(
          "OOPS!",
          "Wrong Email or Password",
          [{ text: "Try Again" }],
          { cancelable: false }
        );
      })
      .addCase(signUpByEmail.pending, state => state.isLoading = true)
      .addCase(signUpByEmail.fulfilled, (state, action)=> {

      })
  },
});

The error arises when setting state.isLoading = true, however, when breaking it into a separate line as shown below, no error occurs:

    export const authSlice = createSlice({
  name: "auth",
  initialState: {
    credentials: {},
    isLoading: false,
  },
  reducers: {
    isLoading: (state) => {
      state.isLoading = !state.isLoading;
    },
  },
  extraReducers: (builder) => {
    builder
      .addCase(signInByEmail.fulfilled, (state, action) => {
        state.credentials = action.payload;
      })
      .addCase(signInByEmail.rejected, (state, action) => {
        Alert.alert(
          "OOPS!",
          "Wrong Email or Password",
          [{ text: "Try Again" }],
          { cancelable: false }
        );
      })
      .addCase(signUpByEmail.pending, (state, action) => {
          state.isLoading = true
      })
      .addCase(signUpByEmail.fulfilled, (state, action)=> {

      })
  },
});

Any insight on what might be causing this error?

Error message received:

No overload matches this call. Overload 1 of 2, '(actionCreator: AsyncThunkPendingActionCreator<{ email: string; password: string; }>, reducer: CaseReducer<{ credentials: {}; isLoading: boolean; }, PayloadAction<undefined, string, { ...; }, never>>): ActionReducerMapBuilder<...>', gave the following error. Type 'boolean' is not assignable to type 'void | { credentials: {}; isLoading: boolean; }'. Overload 2 of 2, '(type: string, reducer: CaseReducer<{ credentials: {}; isLoading: boolean; }, Action>):

Answer №1

The issue arises from the output of your reducer function. When it works, you are not actually returning anything. The function is void and directly modifies the draft state.

.addCase(signUpByEmail.pending, (state, action) => {
     state.isLoading = true
})

There is an alternate syntax where you do return a new state to replace the current one, like this:

.addCase(signUpByEmail.pending, (state, action) => ({...state, isLoading: true}))

However, the state being returned must be a complete state object.

Type 'boolean' is not assignable to type 'void | { credentials: {}; isLoading: boolean; }'

This error indicates that the two valid return types are either void as in the first case or the complete state object { credentials: {}; isLoading: boolean; } as shown in the second example.

The error also points out that you are returning a boolean. This is because arrow functions without braces always return something.

This function a modifies the object and returns void / undefined:

const a = (num: {n: number}): void => { num.n = 1; }

When we omit the curly braces {}, the expression's result is returned. Here, we modify the object and also return 1.

const b = (num: {n: number}): number => num.n = 1;

Test it out!

To summarize, using braces is crucial to prevent accidental return values when setting state.isLoading = true. Without them, you inadvertently return true, which is not a valid return type for a reducer function.

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

Using Typescript to add an element to a specific index in an array

Currently, I am engaged in a project using Angular2 and Firebase. My goal is to consolidate all query results under a single key called this.guestPush. Within my project, there is a multiple select element with different user levels - specifically 4, 6, ...

Steps to successfully pass a reference from a parent component to a child component that utilizes TouchableOpacity in React Native

I am facing an issue with passing a transitioning ref from a parent Transitioning view to a child component: const transition = ( <Transition.Together> <Transition.In type="fade" durationMs={300} /> <Transition.Change /&g ...

Service call delay not displayed on screen

I have a function that I execute in my component's ngOnInit lifecycle hook. This function calls a service to fetch data and populate an array. Once that array is filled, I then call another service method using the data from the first array to populat ...

Managing state in React using UseState along with an asynchronous API request

In my T3 app, I'm using TypeScript, React, Next.js, prisma, and tRPC. The header in my app displays the number of credits a user has. To fetch this data, I make an API call which can take some time to return a response. Since I use the credit amount a ...

"Unexpected token l in JSON at position 0" is causing an error, yet miraculously the code still functions - how is this possible?

Recently delving into the world of websockets with Go for the first time and encountering a strange error that does not disrupt the program flow. The client in use is a ReactJS single page application. JavaScript Client: const socket = new WebSocket(&quo ...

Converting a constant array of objects in Typescript into a typed index lookup object

const vehicles = [ { id: 'id1', name: 'bike' }, { id: 'id2', name: 'scooter' }, { id: 'id3', name: 'motorcycle' }, ] as const; type VehicleId = typeof vehicles[number]['id']; cons ...

Pictures failing to load following deployment - React application hosted on Azure Static Web Apps

I've created a website using react and typescript, and I've successfully deployed it using Azure Static Web Apps. While everything works perfectly on localhost, the published version doesn't display any app images. Upon checking the console ...

Executing a function in the view/template with Angular 2+

Whenever a function is called in the view of an Angular component, it seems to be executed repeatedly. A typical example of this scenario can be seen below: nightclub.component.ts import { Component } from '@angular/core'; @Component({ selec ...

What impact does nesting components have on performance and rendering capabilities?

Although this question may appear simple on the surface, it delves into a deeper understanding of the fundamentals of react. This scenario arose during a project discussion with some coworkers: Let's consider a straightforward situation (as illustrat ...

Tips for instructing kysely key-gen to utilize basic data types for mapping database tables

While using the kysely-codegen tool to automatically create all models from my database, I have noticed a peculiar behavior. It seems to be adding a Generated type to every field instead of generating only number or boolean. Any idea why this is happening? ...

Angular is experiencing difficulty locating the routing path for the auxiliary `router-outlet`

Exploring the intricacies of routing in Angular to gain a deeper understanding of the concept. Encountering an issue where I am receiving an exception NG04002: Cannot match any routes. URL Segment: 'about' when attempting to click on the About li ...

Steps to access a Request object within a Controller

I am currently working with Express and Typescript, utilizing Controllers for managing requests. In an attempt to create a BaseController that includes the Request and Response objects for each request, I wrote the following code snippet. However, it see ...

Exploring the world of Typescript TSX with the power of generic

Introducing JSX syntax support in Typescript opens up new possibilities. I have an expression that functions smoothly with traditional *.ts files, but encounters issues with *.tsx files: const f = <T1>(arg1: T1) => <T2>(arg2: T2) => { ...

Currently in the process of executing 'yarn build' to complete the integration of the salesforce plugin, encountering a few error messages along the way

I've been referencing the Github repository at this link for my project. Following the instructions in the readme file, I proceeded with running a series of commands which resulted in some issues. The commands executed were: yarn install sfdx plugi ...

Display an error message whenever the mouse leaves the input field

Can someone please help me with how to display an error message in Angular4 when the input field is required and the mouse leaves the input? I want the error to show only when the mouse leaves the input, not while I am typing within the input field. Here ...

In an Electron-React-Typescript-Webpack application, it is important to note that the target is not a DOM

Rendering seems to be working fine for the mainWindow. webpack.config.js : var renderer_config = { mode: isEnvProduction ? 'production' : 'development', entry: { app: './src/app/index.tsx', //app_A: './src/a ...

Updating a variable in Nuxt 3 using vue.js

Recently, I started experimenting with Nuxt 3 and Vue 3. All I want is a simple value change when clicking on my div tag. <a id="change" @click="changeValue()">{{value}}</a> <script lang="ts" setup> let val ...

Executing TypeScript compiled code in NodeJS from an HTML file

Being a novice in the world of NodeJS, I am currently diving into the realm of TypeScript. While navigating through Microsoft's TypeScript-Node-Starter, I stumbled upon a query regarding the functionality of the application. Here's what I' ...

Encountering a Issue with Http module in Angular

When attempting to call my API using HttpModule, an error is being thrown upon starting the server (please refer to the screenshot). Error Image The error arises when I try to make a call to the API from the service using Http.post method. Here is my app ...

Retrieve distinct values for the keys from an object array in JavaScript

Here is the structure of my array: const arr1 = [ { "Param1": "20", "Param2": ""8", "Param3": "11", "Param4": "4", "Param5": "18", ...