1

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, ); 
3
  • Show minimal represantation of you problem, how is actions.loadCountries looks like? Is it a function? How to create a Minimal, Reproducible Example Commented Jul 17, 2020 at 16:05
  • It would also be helpful to show your reducer and actions. Especially if some of them are working fine and you're only having an issue with this particular action. Commented Jul 17, 2020 at 16:37
  • I've updated the code on the original posting. Dispach works and delivers the correct JSON using saga if its called on a function that is for example attached to another event, like onChange or onClick. I am using github.com/react-boilerplate/react-boilerplate-cra-template starter with typescript. Commented Jul 17, 2020 at 16:50

1 Answer 1

2

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

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

Sign up to request clarification or add additional context in comments.

1 Comment

Awesome. That did the trick Vitalik! Thank you for that!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.