TaBiLo
TaBiLo

Reputation: 41

Property 'then' does not exist on type '(dispatch: any) => Promise<any>'.ts(2339)

 const updateContent = (values: any) => {

    brands.map((brand: any) => {
      if (brand.brandName === values.brand) {
        values.brand = brand.id;
      }
    })
    
    dispatch(updateProduct(currentProduct.id, values))
    .then(response => {
      props.history.push("/products");
    })
    .catch(e => {
      console.log(e);
    });
  };

enter image description here

I use it in js then ok but use it in typescript then got this error. How to use dispatch().then() in typescript. Please show me. Thanks!!!

Upvotes: 2

Views: 7136

Answers (1)

markerikson
markerikson

Reputation: 67469

This almost always means that you're using the plain version of the Dispatch type that comes with React-Redux by default, which does not know that thunks are dispatchable, and thus does not know that dispatching a thunk may return a promise.

You need to tell TS that you're using the specific version of Dispatch that includes the thunk middleware. Per the instructions in our TS usage guide docs, the right approach is to infer an AppDispatch type from your store, and then create a pre-typed useAppDispatch hook with that type:

// app/store.ts
import { configureStore } from '@reduxjs/toolkit'

const store = configureStore({
  reducer: {
    posts: postsReducer,
    comments: commentsReducer,
    users: usersReducer
  }
})

// Infer the `RootState` and `AppDispatch` types from the store itself
export type RootState = ReturnType<typeof store.getState>
// Inferred type: {posts: PostsState, comments: CommentsState, users: UsersState}
export type AppDispatch = typeof store.dispatch


// app/hooks.ts
import { TypedUseSelectorHook, useDispatch, useSelector } from 'react-redux'
import type { RootState, AppDispatch } from './store'

// Use throughout your app instead of plain `useDispatch` and `useSelector`
export const useAppDispatch = () => useDispatch<AppDispatch>()
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector

// features/counter/Counter.tsx
import React, { useState } from 'react'

import { useAppSelector, useAppDispatch } from 'app/hooks'

import { decrement, increment } from './counterSlice'

export function Counter() {
  // The `state` arg is correctly typed as `RootState` already
  const count = useAppSelector(state => state.counter.value)
  const dispatch = useAppDispatch()

  // omit rendering logic
}

Upvotes: 3

Related Questions