0

I currently have a listenerMiddleware that dispatches login after signup is dispatched. However, I only want to dispatch login IF signup is fulfilled.

//Store.js

listenerMiddleWare.startListening({
    matcher: isAnyOf(signup),
    effect: async (action, listenerAPI) => {
        listenerAPI.cancelActiveListeners();
        await listenerAPI.delay(50)
        listenerAPI.dispatch(login(action.payload))
    }
})
//userSlice.js 

export const signup = createAsyncThunk(
    'userAuth/signup',
    async (payload, thunkAPI) => {
        const { email, password } = payload
        const result = await fetch(
            signupPath, {
            mode: 'cors',
            credentials: 'include',
            method: "post",
            body: JSON.stringify({ email, password }),
            headers: {
                'Content-Type': 'application/json'
            }
        }
        )
        return result.json()
    }
)

export const login = createAsyncThunk(
    'userAuth/login',
    async (payload, thunkAPI) => {
        const { email, password } = payload
        const result = await fetch(
            loginPath, {
            mode: 'cors',
            credentials: 'include',
            method: 'post',
            body: JSON.stringify({ email, password }),
            headers: {
                'Content-Type': 'application/json'
            },
        }
        )
        if (!result.ok) {
            return thunkAPI.rejectWithValue({
                status: result.status,
                message: await result.text(),
            });
        }

        return result.json()

    }
)

How can i approach this problem? thanks

benwl
  • 366
  • 2
  • 17

1 Answers1

1

Use isAFulfilledAction

listenerMiddleWare.startListening({
    matcher: isAFulfilledAction(signup),
    effect: async (action, listenerAPI) => {
        listenerAPI.cancelActiveListeners();
        await listenerAPI.delay(50)
        listenerAPI.dispatch(login(action.payload))
    }
})
Medet Tleukabiluly
  • 11,662
  • 3
  • 34
  • 69
  • could you elaborate on the solution? I am having trouble initializing isFulfilled per the docs – benwl Sep 22 '22 at 23:09