0

I start working in a redux project with redux and it's an entirely chaos, I set up an a Store as interface, like this:

interface Store {
  ads: {
    loading: boolean;
    data: Ad[];
    errors: Error;
    isPro: boolean; 
  };
}

interface Ad {
  id: any;
  title: any;
  body: any;
  price: any;
  latitude: any;
  longitude: any;
}

I have this constant to refer as an action to dispatch after:

export const TYPE_ADD_JOB_ANNOUNCEMENT_REQUEST = "action/addJobAnnouncementRequest";

And then i have my reducer:

   import {
  TYPE_ADD_JOB_ANNOUNCEMENT_REQUEST, 
} from "../constants/actions";

export const reducer = (Store: Store, action: any) => {
  switch (action.type) {

    case TYPE_ADD_JOB_ANNOUNCEMENT_REQUEST:
      console.log("Test");
      return {
        ...Store,
        annuncio: [...Store.ads.data, action.payload]
      };

    default:
      console.log("dont return nothing");
      break;
  }
  return Store;
};

I already the ReduxDevTools working, i test it with different console log and it work fine, now why when the reduxdevotools try to dispatch an action with the payload, (Example:

{
  type: 'action/addJobAnnouncementRequest',
  payload: { title: "test" }
}

It give me different errors if i try different test but with the same mode, like

store is undefinied,

or

cannot read property "ads"

I think there is a problem with my javascript syntax or i dont know, can anyone help me?

Nicola
  • 353
  • 1
  • 2
  • 13
  • We need to see more of your reducer. The interface says `ads` is there, but we cant see if thats true. It also looks like you might be trying to use the interface as the state object, but can't tell – Brian Thompson Nov 20 '19 at 14:23
  • Edited bro, can you give a look? – Nicola Nov 20 '19 at 14:34

1 Answers1

0

You should also initialize your state object as it looks like that is where your error about ads is coming from. You can use store or Store instead of state if you choose.

const initialState: Store = {
  ads: {
    loading: false,
    data: [],
    errors: '',
    isPro: false, 
  };
}

export const reducer = (state = initialState, action: any) => {
  switch (action.type) {
    case TYPE_ADD_JOB_ANNOUNCEMENT_REQUEST:
      return {
        ...state,
        ads: [...state.ads.data, action.payload] // I'm assuming you meant `ads` here?
      };

    default:
      return state;
  }
};
Brian Thompson
  • 13,263
  • 4
  • 23
  • 43
  • i forget to say, its typescript, its the same? – Nicola Nov 20 '19 at 14:49
  • Well since the typings get stripped out before it ever gets to the browser, it might not throw an error, but it could error in the compiler. Not 100% sure. I think the main issue is initializing the reducer. – Brian Thompson Nov 20 '19 at 14:53
  • Looking into if further, I don't think the same names are a problem [reference](https://stackoverflow.com/a/49798480/9381601). Personally I just find it confusing. But I'll remove that part from my answer – Brian Thompson Nov 20 '19 at 14:54