Iggee Xy
Iggee Xy

Reputation: 103

Property 'addCase' does not exist on type 'WritableDraft<search>' in the builder argument of extra reducers

I am new to using typescript with redux toolkit and I am running into a problem with addCase not existing on the builder callback function in my extraReducers. I don't see any similar situation online as mine and suspect I am missing something very simple. However, I can't seem to find it.

Here 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";
              
        });
     }    
 }
})

I am getting an error for all of the .addCase properties: enter image description here

Am I missing something here?

Upvotes: 5

Views: 3375

Answers (1)

hannojg
hannojg

Reputation: 1117

You placed the extraReducers in your code example inside the reducers object. Put it outside of it, change it to:


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

Upvotes: 18

Related Questions