sam
sam

Reputation: 81

Dispatch is not firing inside useEffect on you page load

Im trying to initiate a dispatch actions within useEffect as the page loads, in order to retrieve a JSON and populate an object.

The dispatch functions if it was called separately thorough another call works just fine, and useEffect also handles other logic, but when these two are combined, the dispatch action is not being triggered from within. I also wrote a callback function and tried calling that from within useEffect without any luck. Any feedback would be appreciated.


const dispatch = useDispatch();

useEffect(() => {
  dispatch(actions.loadCountries);
}, [dispatch]);

---------------------------
Using redux toolkit and create slice

export const initialState: ContainerState = {
  countriesLoading: false,
  countriesError: null,
  countries: [],
};

const initiateSlice = createSlice({
  name: 'home',
  initialState,
  reducers: {
    loadCountries(state) {
      state.countriesLoading = true;
      state.countriesError = null;
      state.countries = [];
    },
    countriesLoaded(state, action: PayloadAction<ICountry[]>) {
      state.countries = action.payload;
      state.countriesLoading = false;
    },
    countriesError(state, action: PayloadAction<ErrorType>) {
      state.countriesError = action.payload;
      state.countriesLoading = false;
    },
  },
});

export const { actions, reducer, name: sliceKey } = initiateSlice;


--------------
Selector

const selectDomain = (state: RootState) => state.initiate || initialState;

export const selectCountriesLoading = createSelector(
  [selectDomain],
  initiateState => initiateState.countriesLoading,
);

export const selectCountriesError = createSelector(
  [selectDomain],
  initiateState => initiateState.countriesError,
);

export const selectCountries = createSelector(
  [selectDomain],
  initiateState => initiateState.countries,
);

Upvotes: 1

Views: 824

Answers (1)

Vitali T
Vitali T

Reputation: 349

hmm... try to add () to the end of the action name

dispatch(actions.loadCountries**()**)

Upvotes: 2

Related Questions