0

Say had a reducer for a certain state

... function thisFunction (
state = new state, 
action
)
{
switch(type) {
     case INIT_STATE:
        return {
          ...state, 
          ...action.state
        }
        default:
          return {
           certainProp: setCertainProp(state.certainProp, action)
        }

and my reducer for it

function setCertainProp(state = {}, action) {
     const { type } = action
         switch (type) {
             case SET_CERTAIN_PROP:
                 return action.certainProp
             default:
                 return state

and now my action

function setCertainPropAction(prop){
    return {
        type: SET_CERTAIN_PROP
        action: prop
     }
}

now inside my container in a componentDidMount or useEffect I want certainProp's value to come from a fetch call

useEffect(() => {
    fetchCertainProp().then(response => setCertainPropAction(response)
}, [])

my question is, is it possible to completely remove the useEffect here and call the fetchCertainProp() from inside the initialization of certainProp within the reducer? I have access to redux-thunks but I haven't seen an example of how this would be possible. I don't want to add an unnecessary useEffect if I don't need too.

4156
  • 380
  • 4
  • 17
  • If the `fetchCertainProp` function has a side effect, you can't use it inside reducer function. Reducer function should be pure. – Lin Du Sep 09 '22 at 04:52
  • You need to use an async action (like thunk) to get this value into the store, or alternatively fetch the value *before* the redux store itself is created (where the app is bootstrapped usually) - so that the value is already present when the initialState is set. – timotgl Sep 09 '22 at 10:20

0 Answers0