kyrylolv
kyrylolv

Reputation: 320

TypeScript errors in rootReducer and Action

I am doing a project that shows pictures from NASA's api and got some errors that I don't know how to solve. The first one is in store's index.ts, in rootReducer, where I use combineReducers. Type 'typeof PostsReducer' is not assignable to type 'Reducer<unknown, any>'

And the second one is in posts action, Type 'AxiosResponse<Post[]>' is missing the following properties from type 'Post[]'

Here are the action and reducer:

import { createActionCreators } from "immer-reducer";

import { PostsReducer } from "../reducers/posts";
import { PostsRequestBody } from "../../api/main-protected";
import { AsyncAction } from "./common";

export const postsActions = createActionCreators(PostsReducer);

export type PostsActions = ReturnType<typeof postsActions.setPosts>;

export const getPosts =
  (body: PostsRequestBody): AsyncAction =>
  async (dispatch, _, { mainProtectedApi }) => {
    try {
      const posts = await mainProtectedApi.getPosts(body);
      console.log(posts);

      dispatch(postsActions.setPosts(posts));
    } catch (e) {
      console.log(e);
    }
  };

import { createReducerFunction, ImmerReducer } from "immer-reducer";

export interface Post {
  copyright: string;
  date: string;
  explanation: string;
  hdurl: string;
  media_type: string;
  service_version: string;
  title: string;
  url: string;
}

export interface PostsState {
  posts: Post[] | null;
}

const initialState: PostsState = {
  posts: null,
};

export class PostsReducer extends ImmerReducer<PostsState> {
  setPosts(posts: Post[]) {
    this.draftState.posts = posts;
  }
}

export default createReducerFunction(PostsReducer, initialState);
import { createStore, applyMiddleware, compose, combineReducers } from "redux";
import thunk from "redux-thunk";

import MainProtected from "../api/main-protected";
import { PostsActions } from "./actions/posts";
import { PostsReducer } from "./reducers/posts";

export const api = {
  mainProtectedApi: MainProtected.getInstance(),
};

declare global {
  interface Window {
    __REDUX_DEVTOOLS_EXTENSION_COMPOSE__?: typeof compose;
  }
}

const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;

const enhancer = composeEnhancers(
  applyMiddleware(thunk.withExtraArgument(api))
);

const rootReducer = combineReducers({
  PostsReducer,
});

export type State = ReturnType<typeof rootReducer>;
export type Actions = PostsActions;

export default createStore(rootReducer, enhancer);

Upvotes: 1

Views: 246

Answers (1)

kyrylolv
kyrylolv

Reputation: 320

So, I fixed the first problem with the reducer. I was importing the PostsReducer class, not the postsReducer, that is created by createReducerFunction. I solved it by changing the export:

export const postsReducer = createReducerFunction(PostsReducer, initialState);

Upvotes: 1

Related Questions