Q:

combineReducers is overwriting state instead of setting up different states

I'm trying to learn Redux.
I have this action which fetches data:
export const FETCH_SUCCESS = "FETCH_SUCCESS";
import axios from "axios";

export const fetchData = () => {
  return async dispatch => {
    try {
      const result = await axios(
        `url`
      );
      dispatch({ type: FETCH_SUCCESS, payload: { result } });
    } catch (error) {
      console.log(error);
    }
  };
};

And this reducer:
import { FETCH_SUCCESS } from "../actions/mainCategories";

const initialState = {
  mainCategories: []
};

const mainCategoriesReducer = (state = initialState, action) => {
  switch (action.type) {
    case FETCH_SUCCESS:
      return { data: action.payload.result.data };
    default:
      return state;
  }
};

export default mainCategoriesReducer;

I use this twice, one for the mainCategories and the exact same code for my subcategories but in different files, so that I can combine it in App.js like this:
import mainCategoriesReducer from "./store/reducers/mainCategories";
import subCategoriesReducer from "./store/reducers/subCategories";

const rootReducer = combineReducers({
  mainCategories: mainCategoriesReducer,
  subCategories: subCategoriesReducer,
});

const store = createStore(rootReducer, applyMiddleware(ReduxThunk));

I wrap the Provider with the stored store around my App:
<Provider store={store}>
   <App />
</Provider>

In the components I use it like this:
import { fetchData } from "../store/actions/mainCategories";

const mainCategories = useSelector(state => state.mainCategories);

  useEffect(() => {
    dispatch(fetchData());
  }, [dispatch]);

And the same for the subCategories but with the corresponding imports and states (state.subCategories)
Everything is working as expected. When the App loads, it fetches my mainCategories. I can navigate to my subcategories but when I go back, the mainCategories are overwritten by the subCategories.
It seems like the combineReducers merges / overwrites instead of creating the different states. What am I doing wrong? Thank you

A:

You need different type names to make this work. When you combine reducers, it's important that the app knows how to route your actions to the correct store. If you want to call them both FETCH_SUCCESS, I think that's fine, but add the path in front of the definition:
in your main categories actions file:
export const FETCH_SUCCESS = "mainCategories/FETCH_SUCCESS";

and in your subcategories actions file:
export const FETCH_SUCCESS = "subCategories/FETCH_SUCCESS";

That should work, but you may also need to rename the FETCH_SUCCESS variables if it's still not working.

