The issue arises when trying to access the 'addCase' property on the type 'WritableDraft<search>' within the builder argument of extra reducers

I am a beginner when it comes to using TypeScript with Redux Toolkit and I have encountered an issue with addCase not being available on the builder callback function in my extraReducers. I haven't been able to find a similar situation online, and I suspect that I might be overlooking something very simple. However, despite my efforts, I can't seem to pinpoint the problem.

Below is my createAsyncThunk:

type myData = object[]

export const fetchResults = createAsyncThunk
(
    "search/fetchResults", async (searchTerm: string) => {
       try {
          
          const url:string = `https://www.googleapis.com/books/v1/volumes?q=${searchTerm}keyes&key=${process.env.REACT_APP_MY_API_KEY}`
          const response = await axios.get(url);//where you want to fetch data
          return (await response.data()) as myData;
        } catch (error) {
           return error
        }
  });

And here is my slice with extraReducers:

interface searchInterface {
    field: string
    result: object[]
    loading: 'idle' | 'loading' | 'loaded' | 'failed'
}

const initialState: searchInterface = {
    field: "",
    result: [],
    loading:"idle"
}

const searchSlice = createSlice({
 name: 'search',
 initialState,
 reducers: {
     fieldChange(state, action: PayloadAction<string>)
     {
         state.field = action.payload
     },
     
 extraReducers: (builder) => {
        builder.addCase(fetchResults.pending, (state: searchInterface) => {
          state.result = [];
          state.loading = "loading";
        });
        builder.addCase(
            fetchResults.fulfilled, (state: searchInterface, action:PayloadAction<object[]>) => {
              state.result = action.payload;
              state.loading = "loaded";
        });
        builder.addCase(
            fetchResults.rejected, (state: searchInterface) => {
              state.loading = "failed";
              
        });
     }    
 }
})

All of the .addCase properties are triggering an error: https://i.sstatic.net/hzHy0.png

Is there something obvious that I am overlooking?

Answer №1

The extraReducers in the given code snippet is situated within the reducers object. To correct this, it should be placed outside of it as follows:


const searchSlice = createSlice({
 name: 'search',
 initialState,
 reducers: {
     fieldChange(state, action: PayloadAction<string>)
     {
         state.field = action.payload
     },
 }, // 👀 Make sure to close the curly bracket here    
 extraReducers: (builder) => {

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

unable to retrieve information from the redis cache

Attempting to retrieve data from cache using the readData function in the controller file. Encountering an issue where the someVal variable is initially undefined after calling readData, but eventually gets populated with data after receiving a callback ...

Using TypeScript to create a unique object type that is mapped with generics for each key

Suppose I have a type representing an array of two items: a list of parameters and a function with arguments corresponding to the parameters. I've created a handy function to infer the generic type for easy use. type MapParamsToFunction<A extends a ...

Whenever I try to import a function, I encounter the error message "no exported member."

I am facing an issue with my node/typescript application where I am attempting to import a function from another file. In order to export it, I utilized exports.coolFunc = coolFunc, and for importing, I used import {coolFunc} from '../controller/coolS ...

What is causing the undefined value for the http used in this function?

My Code Component import { Component, OnInit } from '@angular/core'; import { Http } from '@angular/http'; @Component({ selector: 'app-root', template: '<button id="testBtn"></button>' }) export c ...

Looking for guidance on locating Typescript type definitions?

As a newcomer to Typescript, I have recently delved into using it with React. While I have grasped the fundamentals of TS, I find myself perplexed when it comes to discovering or deriving complex types. For example, in React, when dealing with an input el ...

Checking a TypeScript project with various start points for linting

Within my extensive application that is constructed using webpack, there are numerous entry points that are generated dynamically. Each entry point requires specific target files to be created during the build process. I have already realized that when bu ...

Encountering Flow type errors when declaring global variables in React

type Props = { checkedItems:any }; class MyApp extends Component<Props> { constructor(props) { super(props); this.checkedItems = []; } } In this code snippet, I am utilizing Flow for type checking within a React class component. However ...

Combining data from various API calls into one cohesive array using RXJS

My RXJS Pipeline is structured as follows: const logs: number[] = [1, 2, 3, 4]; const url = 'http://some-url-here.com'; const pipeline = from(logs).pipe( switchMap(logId => this.callEndpoint(url, logId).pipe(map(response => response. ...

The attribute 'Error' is not available for the object of type 'MovieData | ResponseError'. This attribute is also not present in objects of type 'MovieData'

Question Answered I am currently working with two interfaces, MovieData and ResponseError. export interface MovieData { Poster: string; Title: string; Plot: string; imdbID: string; } The ResponseError interface looks like this: export interface R ...

Populate input fields in HTML using Angular 4

Within my angular 4 project, I am facing the challenge of setting a value in an input field and in a MatSelect without relying on any binding. Here is the HTML structure: <div class="row search-component"> <div class="col-md-5 no-padding-rig ...

The implementation of TypeScript 3.5 resulted in a malfunction where the imported namespace was unable to locate the Enum during runtime

I recently upgraded an older Angular.js application from Typescript 2.7 to 3.5 and successfully compiled it using tsc.exe. During application runtime, I encountered an error message in certain parts of the code: TypeError: Cannot read property 'Enu ...

Fixing the (Missing: any) error in a create-react-app project using TypeScript

One of the challenges I'm facing is when I call the BookTracker component in my root App.tsx file, specifically with the prop book={MY_MOCK}. type BookParamsTypes = { title: string; pubDate: number; //... rest }; import { BookParamsTypes } fro ...

The element fa-icon is unrecognized within the Reusable Module

Can anyone help me understand why I am encountering this issue with a reusable Module (or what mistake I have made)? ERROR Error: Uncaught (in promise): Error: Template parse errors: 'fa-icon' is not a known element Just to clarify: fa-icon ...

Tips for maintaining a healthy balance of tasks in libuv during IO operations

Utilizing Typescript and libuv for IO operations is crucial. In my current situation, I am generating a fingerprint hash of a particular file. Let's say the input file size is approximately 1TB. To obtain the file's fingerprint, one method involv ...

How can I assign a specific class to certain elements within an *ngFor loop in Angular?

I have a situation where I am utilizing the *ngFor directive to display table data with the help of *ngFor="let record of records". In this scenario, I am looking to assign a custom CSS class to the 'record' based on specific conditions; for exam ...

Leverage the power of TypeScript by enabling the noImplicitAny flag when working

Currently, I am looking to activate the noImplicitAny flag in my compiler. My main issue lies with utilizing lodash/fp as there are no typings available at this moment. Due to this, the compiler is generating errors due to the absence of a definition file ...

JavaScript: specify parameters for function inputs

I'm curious about optimizing Javascript/Typescript functions arguments for clean code. To demonstrate, let's consider a basic example. Imagine I have a React component with a view property as props: <Grid view="Horizontal" /> ty ...

Cross-component communication in Angular

I'm currently developing a web-based application using angular version 6. Within my application, there is a component that contains another component as its child. In the parent component, there is a specific function that I would like to invoke when ...

What exactly constitutes an error in a problem?

There is no error @Component({ selector: 'app-root', template: '<h1>InlineTemplate</h1>', styles: ['h1{color:red;}']}) However, after pressing Enter, an error occurs @Component({ selector: ' app-root', ...

Setting up AngularJS 1.5.x to function seamlessly with SystemJS and TypeScript

I'm looking to keep all my code in AngularJS 1.x while also preparing it for an easy upgrade to AngularJS 2 in the future. To align my code with Angular 2 standards, I am interested in using TypeScript and SystemJS in version 1.5.x initially. Is ther ...