Debounce in redux-tool-kit - react-hooks

I'm Trying to debounce below API call with using lodash debounce
export const getProfile = createAsyncThunk(
GET_PROFILE,
async (amount: any, { rejectWithValue }: any) => {
try {
const response = await API.Get(EndPoint.GET_PROFILE)
console.log(response)
return response.data
} catch (error: any) {
amount.failCallBack(error?.response?.data?.msg || 'something_went_wrong')
return rejectWithValue(error?.code || 'Something went wrong..!')
}
}
)
above function is worked without any errors and fetch data able to see inside fullfilled of the action
so i tried to implement debounce as below way
export const getProfile = createAsyncThunk(
GET_PROFILE,
debounce(async (amount: any, { rejectWithValue }: any) => {
try {
const response = await API.Get(EndPoint.GET_PROFILE)
console.log(response)
return response.data
} catch (error: any) {
amount.failCallBack(error?.response?.data?.msg || 'something_went_wrong')
return rejectWithValue(error?.code || 'Something went wrong..!')
}
}, 5000)
)
Now there is no any exceptions in web app and when i console log the fullfilled action it shows
payload as undefined
{
"type": "login/getProfile/fulfilled",
"meta": {
"arg": {
"data": "login"
},
payload: undefined,
"requestId": "8pfalpIzFl8nNOgi2jRcb",
"requestStatus": "fulfilled"
}
}
any suggestions for fix this issue.
thanks in advance

Don't debounce the payload creator - debounce dispatching the thunk action. And since you probably don't want to that in your component, do it in a manual thunk
const getProfile = createAsyncThunk( ... normal definition ... );
const debounced = debounce((arg, dispatch) => dispatch(getProfile(arg)), 5000);
const debouncedGetProfile = (arg) => (dispatch) => debounced(arg, dispatch)
and then use that
dispatch(debouncedGetProfile(amount))

Related

Test custom react hooks for promise reject with testing library react hooks

I have a custom react hook, just to make a GET request with axios, and
the file named as: useAxiosGet.ts,
and the code is:
import {useMemo, useState} from "react";
import axios, {AxiosResponse} from "axios";
interface ErrorBody {
code: string,
message: string
}
export interface ErrorResponse {
status: number,
errorBody?: ErrorBody
}
export const useAxiosGet = <TResponse>(
requestUrl: string,
) => {
const [data, setData] = useState<TResponse>();
const [error, setError] = useState<ErrorResponse>();
const [loading, setLoading] = useState(false);
const getData = useMemo(() => {
return () => {
setLoading(true);
setError(undefined);
return axios.get(requestUrl)
.then((response: AxiosResponse<TResponse>) => {
const responseData = response.data;
setData(responseData);//update the date
return responseData
})
.catch(err => {
const errorResponse = {status: err.response.status, errorBody: err.response.data}
setError(errorResponse); //update the error
return Promise.reject(errorResponse) //return a Promise.reject
}).finally(() => {
setLoading(false)
});
};
}, []);
return {data, getData, setData, loading, error}
};
I made the resolved case test passed, but the reject case does not, and you can see that
I am returning the Promise.reject(errorResponse) in the.catch(), and I think this is the key point for the failed test. And my test code looks like below:
import {act, renderHook} from '#testing-library/react-hooks'
import axios from 'axios';
import MockAdapter from "axios-mock-adapter";
import {useAxiosGet} from "./useAxiosGet";
interface TProfile {
name: string
}
describe('useAxiosGet', () => {
let mockAxios: MockAdapter;
beforeAll(() => {
mockAxios = new MockAdapter(axios);
})
afterEach(() => {
mockAxios.reset()
})
afterAll(() => {
mockAxios.restore()
})
//This test passed
test('should get data for success request', async () => {
mockAxios.onGet("/id/1").reply(200, {name: 'nana'})
const {result, waitForNextUpdate} = renderHook(() => useAxiosGet<TProfile>('/id/1',))
act(() => {
result.current.getData()
})
await waitForNextUpdate()
expect(result.current.data).toStrictEqual({name: 'nana'})
expect(result.current.loading).toBeFalsy()
expect(result.current.error).toBe(undefined)
});
//This test not passed
test('should get error for failed request', async () => {
const errorBody = {
'code': 'NOT_FOUND',
'message': 'id 1 not found',
};
//Mock the request with a failed HTTP response
mockAxios.onGet("/id/1").reply(404, errorBody)
const {result, waitForValueToChange} = renderHook(() => useAxiosGet<TProfile>('/id/1',))
await waitForValueToChange(() => result.current.getData());
let errorResponse = {
status: 404,
errorBody: errorBody
};
expect(result.current.data).toStrictEqual(undefined);
expect(result.current.error).toStrictEqual(errorResponse);
})
})
I would like to test after the API called, the result.current.error should be the errorResponse expected, but I always get undefined :
test failed screenshot
I know there are something wrong with the test code, but I do not know the correct way to test the reject case, any one know how to do it?

Providing two combined Reducers for my redux saga store prevents my websocket channel message from triggering, but only one does not?

Configured my store this way with redux toolkit for sure
const rootReducer = combineReducers({
someReducer,
systemsConfigs
});
const store = return configureStore({
devTools: true,
reducer: rootReducer ,
// middleware: [middleware, logger],
middleware: (getDefaultMiddleware) => getDefaultMiddleware({ thunk: false }).concat(middleware),
});
middleware.run(sagaRoot)
And thats my channel i am connecting to it
export function createSocketChannel(
productId: ProductId,
pair: string,
createSocket = () => new WebSocket('wss://somewebsocket')
) {
return eventChannel<SocketEvent>((emitter) => {
const socket_OrderBook = createSocket();
socket_OrderBook.addEventListener('open', () => {
emitter({
type: 'connection-established',
payload: true,
});
socket_OrderBook.send(
`subscribe-asdqwe`
);
});
socket_OrderBook.addEventListener('message', (event) => {
if (event.data?.includes('bids')) {
emitter({
type: 'message',
payload: JSON.parse(event.data),
});
//
}
});
socket_OrderBook.addEventListener('close', (event: any) => {
emitter(new SocketClosedByServer());
});
return () => {
if (socket_OrderBook.readyState === WebSocket.OPEN) {
socket_OrderBook.send(
`unsubscribe-order-book-${pair}`
);
}
if (socket_OrderBook.readyState === WebSocket.OPEN || socket_OrderBook.readyState === WebSocket.CONNECTING) {
socket_OrderBook.close();
}
};
}, buffers.expanding<SocketEvent>());
}
And here's how my saga connecting handlers looks like
export function* handleConnectingSocket(ctx: SagaContext) {
try {
const productId = yield select((state: State) => state.productId);
const requested_pair = yield select((state: State) => state.requested_pair);
if (ctx.socketChannel === null) {
ctx.socketChannel = yield call(createSocketChannel, productId, requested_pair);
}
//
const message: SocketEvent = yield take(ctx.socketChannel!);
if (message.type !== 'connection-established') {
throw new SocketUnexpectedResponseError();
}
yield put(connectedSocket());
} catch (error: any) {
reportError(error);
yield put(
disconnectedSocket({
reason: SocketStateReasons.BAD_CONNECTION,
})
);
}
}
export function* handleConnectedSocket(ctx: SagaContext) {
try {
while (true) {
if (ctx.socketChannel === null) {
break;
}
const events = yield flush(ctx.socketChannel);
const startedExecutingAt = performance.now();
if (Array.isArray(events)) {
const deltas = events.reduce(
(patch, event) => {
if (event.type === 'message') {
patch.bids.push(...event.payload.data?.bids);
patch.asks.push(...event.payload.data?.asks);
//
}
//
return patch;
},
{ bids: [], asks: [] } as SocketMessage
);
if (deltas.bids.length || deltas.asks.length) {
yield putResolve(receivedDeltas(deltas));
}
}
yield call(delayNextDispatch, startedExecutingAt);
}
} catch (error: any) {
reportError(error);
yield put(
disconnectedSocket({
reason: SocketStateReasons.UNKNOWN,
})
);
}
}
After Debugging I got the following:
The Thing is that when I Provide one Reducer to my store the channel works well and data is fetched where as when providing combinedReducers I am getting
an established connection from my handleConnectingSocket generator function
and an empty event array [] from
const events = yield flush(ctx.socketChannel) written in handleConnectedSocket
Tried to clarify as much as possible
ok so I start refactoring my typescript by changing the types, then saw all the places that break, there was a problem in my sagas.tsx.
Ping me if someone faced such an issue in the future

Nest.js handling errors for HttpService

I'm trying to test NestJS's built in HttpService (which is based on Axios). I'm having trouble testing error/exception states though. In my test suite I have:
let client: SomeClearingFirmClient;
const mockConfigService = {
get: jest.fn((type) => {
switch(type) {
case 'someApiBaseUrl': {
return 'http://example.com'
}
case 'someAddAccountEndpoint': {
return '/ClientAccounts/Add';
}
case 'someApiKey': {
return 'some-api-key';
}
default:
return 'test';
}
}),
};
const successfulAdd: AxiosResponse = {
data: {
batchNo: '39cba402-bfa9-424c-b265-1c98204df7ea',
warning: '',
},
status: 200,
statusText: 'OK',
headers: {},
config: {},
};
const failAddAuth: AxiosError = {
code: '401',
config: {},
name: '',
message: 'Not Authorized',
}
const mockHttpService = {
post: jest.fn(),
get: jest.fn(),
}
it('Handles a failure', async () => {
expect.assertions(1);
mockHttpService.post = jest.fn(() => of(failAddAuth));
const module: TestingModule = await Test.createTestingModule({
providers: [
{
provide: ConfigService,
useValue: mockConfigService,
},
{
provide: HttpService,
useValue: mockHttpService,
},
SomeClearingFirmClient,
],
}).compile();
client = module.get<SomeClearingFirmClient>(SomeClearingFirmClient);
const payload = new SomeClearingPayload();
try {
await client.addAccount(payload);
} catch(e) {
console.log('e', e);
}
});
And my implementation is:
async addAccount(payload: any): Promise<SomeAddResponse> {
const addAccountEndpoint = this.configService.get('api.someAddAccountEndpoint');
const url = `${this.baseUrl}${addAccountEndpoint}?apiKey=${this.apiKey}`;
const config = {
headers: {
'Content-Type': 'application/json',
}
};
const response = this.httpService.post(url, payload, config)
.pipe(
map(res => {
return res.data;
}),
catchError(e => {
throw new HttpException(e.response.data, e.response.status);
}),
).toPromise().catch(e => {
throw new HttpException(e.message, e.code);
});
return response;
}
Regardless of whether I use Observables or Promises, I can't get anything to catch. 4xx level errors sail on through as a success. I feel like I remember Axios adding some sort of config option to reject/send an Observable error to subscribers on failures... but I could be imagining that. Am I doing something wrong in my test harness? The other StackOverflow posts I've seen seem to say that piping through catchError should do the trick, but my errors are going through the map operator.
Your mockHttpService seems to return no error, but a value:
mockHttpService.post = jest.fn(() => of(failAddAuth));
What of(failAddAuth) does is to emit a value(failAddAuth) and then complete.
That's why the catchError from this.httpService.post(url, payload, config) will never be reached, because no errors occur.
In order to make sure that catchError is hit, the observable returned by post() must emit an error notification.
You could try this:
// Something to comply with `HttpException`'s arguments
const err = { response: 'resp', status: '4xx' };
mockHttpService.post = jest.fn(() => throwError(err));
throwError(err) is the same as new Observable(s => s.error(err))(Source code).

Nested dispatch function does not get update props

app.js
const mapStateToProps = (state) => {
return {home:state}
}
const mapDispatchToProps = (dispatch) => {
return {
guestLogin: (data)=>{dispatch(guestLogin(data)).then(()=>{
dispatch(initiateTrans(stateProps.home))
})},
};
}
const mergeProps = (stateProps, dispatchProps, ownProps) => {
return Object.assign({}, ownProps, stateProps, dispatchProps,{
initiateTrans: () => dispatchProps.initiateTrans(stateProps.home),
})
}
Action.js
export const guestLogin= (state)=>{
var data={
'email':state.email,
'name':state.name,
'phone_number':state.ph_number,
'phone_code':state.country_code
}
return function(dispatch) {
return dataservice.guestSignup(data).then(res => {
dispatch(afterLoggedGuest(res))
}).catch(error => {
throw(error);
});
}
}
function afterLoggedGuest(result) {
return {type: guestLoginChange, result};
}
export const initiateTrans= (updatedState)=>{
return function(dispatch) {
return dataservice.initiateTransaction(updatedState).then(res => {
console.log("initiateTransaction",res)
}).catch(error => {
throw(error);
});
}
}
Reducer.js
if(action.type === guestLoginChange){
return {
...state,guestData: {
...state.guestData,
Authorization: action.result.authentication ,
auth_token: action.result.auth_token ,
platform: action.result.platform
} ,
}
}
I am having two api requests.. After first api request success i want to update state value then pass that updated state to another api request..
I tried to get the updted props
how to dispatch the initiateTrans with update props
I need to update value at api request success in call back i need to call one more request with updated state value
currently i am not able to get the update props value
I think this is a good use case for thunk (redux-thunk), which is a middleware that allows you to execute multiple dispatches in an action.
You will need to apply the middleware when you configure the initial store (see docs on link above). But then in your actions, you can wrap the code with a dispatch return statement, which gives you access to multiple calls. For example:
export const guestLogin= (state)=>{
return dispatch => {
var data={...} // some data in here
return dataservice.guestSignup(data).then(res => {
dispatch(afterLoggedGuest(res))
}).catch(error => {
throw(error);
// could dispatch here as well...
});
}
}

InfiniteLoader and react-redux

Component InfiniteLoader from react-virtualised requires function passed as property loadMoreRows to have signature like { startIndex: number, stopIndex: number }): Promise.
I'm using redux in my project, so loadMoreRows is a redux action creator like this:
const fetchEntities(start, stop) {
return fetch(`${myUrl}&start=${start}?stop=${stop}`)
}
const loadMoreRows = ({ startIndex, stopIndex }) => {
return (dispatch, getState) => {
return function(dispatch) {
return fetchEntities(startIndex, stopIndex).then(
items => dispatch(simpleAction(items)),
error => console.log(error)
)
}
}
}
after that, this action is connected to react component containing InfiniteLoader using connect function from react-redux.
So I'm not sure, how can I satisfy signature requirement, as redux action creators don't return any value/
eyeinthebrick is correct. A Promise is not a required return value.
When you "connect" a Redux action-creator, invoking it (dispatching it) actually returns a Promise. So for example I think you could do something more like this...
function fetchEntities (start, stop) {
return fetch(`${myUrl}&start=${start}?stop=${stop}`)
}
const loadMoreRows = ({ startIndex, stopIndex }) => {
return async (dispatch, getState) => {
try {
const items = await fetchEntities(startIndex, stopIndex)
await dispatch(simpleAction(items))
} catch (error) {
console.log(error)
}
}
}
At which point InfiniteLoader can just await the returned Redux promise.

Resources