Home > Net >  How to create redux strore with object using typescript?
How to create redux strore with object using typescript?

Time:09-17

I am new to using Redux and Typescript. And I can’t understand the error why the store doesn’t want to accept the reducer when i try to work with object

let store = createStore(counter); //error on counter

it’s the wrong type set in Typescript or the wrong reducer?

error text:

const counter: (state: IPerson, action: any) => number | undefined No overload matches this call. Contribute a translation for #2769

Overload 1 of 2, '(reducer: Reducer<IPerson, any>, enhancer?: StoreEnhancer<unknown, unknown> | undefined): Store<IPerson, any>', gave the following error. Contribute a translation for #2772

Argument of type '(state: IPerson, action: any) => number | undefined' is not assignable to >parameter of type 'Reducer<IPerson, any>'. Translation: I was expecting Reducer<IPerson, any>, but you passed (state: IPerson, action: any) => number | undefined

import React from 'react';
import logo from './logo.svg';
import {createStore} from 'redux'

function App() {

interface IPerson{
  name:string,
  age:number
}

const increment = () => {return {type: 'INCREMENT'}}
const decrement = () => {return {type: 'DECREMENT'}}

const counter = (state:IPerson , action:any) =>{
  switch(action.type){
    case'INCREMENT':
      return state.age   1;
      
    case'DECREMENT':
      return state.age - 1;
  }}
let store = createStore(counter);

store.subscribe(()=>console.log(store.getState()));

  return (
    <div className="App">
      <button onClick={(()=>store.dispatch(increment()))}>increment</button>
      <button onClick={(()=>store.dispatch(decrement()))}>decrement</button>
        <h1>Hello world!</h1>
    </div>
  );
}

export default App;

CodePudding user response:

Your reducer does not return in case the other two cases didn't match.

Generally, you are using a very old style of Redux here (modern Redux is 1/4 of the code) and quite some bad practices (never call store.dispatch in a component!).

I would really recommend you to read about modern Redux and follow the official tutorial instead of following whatever resources you've been reading so far.

  • Related