action.js
export function getLoginStatus() {
return async(dispatch) => {
let token = await getOAuthToken();
let success = await verifyToken(token);
if (success == true) {
dispatch(loginStatus(success));
} else {
console.log("Success: False");
console.log("Token mismatch");
}
return success;
}
}
component.js
componentDidMount() {
this.props.dispatch(splashAction.getLoginStatus())
.then((success) => {
if (success == true) {
Actions.counter()
} else {
console.log("Login not successfull");
}
});
}
However, when I write component.js code with async/await like below I get this error:
Possible Unhandled Promise Rejection (id: 0): undefined is not a function (evaluating 'this.props.dispatch(splashAction.getLoginStatus())')
component.js
async componentDidMount() {
let success = await this.props.dispatch(splashAction.getLoginStatus());
if (success == true) {
Actions.counter()
} else {
console.log("Login not successfull");
}
}
How do I await a getLoginStatus() and then execute the rest of the statements?
Everything works quite well when using .then(). I doubt something is missing in my async/await implementation. trying to figure that out.
The Promise approach
export default function createUser(params) {
const request = axios.post('http://www...', params);
return (dispatch) => {
function onSuccess(success) {
dispatch({ type: CREATE_USER, payload: success });
return success;
}
function onError(error) {
dispatch({ type: ERROR_GENERATED, error });
return error;
}
request.then(success => onSuccess, error => onError);
};
}
The async/await approach
export default function createUser(params) {
return async dispatch => {
function onSuccess(success) {
dispatch({ type: CREATE_USER, payload: success });
return success;
}
function onError(error) {
dispatch({ type: ERROR_GENERATED, error });
return error;
}
try {
const success = await axios.post('http://www...', params);
return onSuccess(success);
} catch (error) {
return onError(error);
}
}
}
Referenced from the Medium post explaining Redux with async/await: https://medium.com/#kkomaz/react-to-async-await-553c43f243e2
Remixing Aspen's answer.
import axios from 'axios'
import * as types from './types'
export function fetchUsers () {
return async dispatch => {
try {
const users = await axios
.get(`https://jsonplaceholder.typicode.com/users`)
.then(res => res.data)
dispatch({
type: types.FETCH_USERS,
payload: users,
})
} catch (err) {
dispatch({
type: types.UPDATE_ERRORS,
payload: [
{
code: 735,
message: err.message,
},
],
})
}
}
}
import * as types from '../actions/types'
const initialErrorsState = []
export default (state = initialErrorsState, { type, payload }) => {
switch (type) {
case types.UPDATE_ERRORS:
return payload.map(error => {
return {
code: error.code,
message: error.message,
}
})
default:
return state
}
}
This will allow you to specify an array of errors unique to an action.
Another remix for async await redux/thunk. I just find this a bit more maintainable and readable when coding a Thunk (a function that wraps an expression to delay its evaluation ~ redux-thunk )
actions.js
import axios from 'axios'
export const FETCHING_DATA = 'FETCHING_DATA'
export const SET_SOME_DATA = 'SET_SOME_DATA'
export const myAction = url => {
return dispatch => {
dispatch({
type: FETCHING_DATA,
fetching: true
})
getSomeAsyncData(dispatch, url)
}
}
async function getSomeAsyncData(dispatch, url) {
try {
const data = await axios.get(url).then(res => res.data)
dispatch({
type: SET_SOME_DATA,
data: data
})
} catch (err) {
dispatch({
type: SET_SOME_DATA,
data: null
})
}
dispatch({
type: FETCHING_DATA,
fetching: false
})
}
reducers.js
import { FETCHING_DATA, SET_SOME_DATA } from './actions'
export const fetching = (state = null, action) => {
switch (action.type) {
case FETCHING_DATA:
return action.fetching
default:
return state
}
}
export const data = (state = null, action) => {
switch (action.type) {
case SET_SOME_DATA:
return action.data
default:
return state
}
}
Possible Unhandled Promise Rejection
Seems like you're missing the .catch(error => {}); on your promise. Try this:
componentDidMount() {
this.props.dispatch(splashAction.getLoginStatus())
.then((success) => {
if (success == true) {
Actions.counter()
} else {
console.log("Login not successfull");
}
})
.catch(err => {
console.error(err.getMessage());
}) ;
}
use dispatch(this.props.splashAction.getLoginStatus()) instead this.props.dispatch(splashAction.getLoginStatus())
Related
Basically i wanted to integrate the mqtt in my react app. I want to connect to the mqtt when user login and disconnect when user logs out.
Firstly i created actions,reducers to dispatch the connection state and get client payload. It's connecting but the mqtt servers seems to be reconnecting in a loop with few secs. I want it to connect once and disconnect user logs out automatically. I globally initiated the mqtt client in the mqqtActions.js.
import { CONNECT_MQTT_FAILURE, CONNECT_MQTT_REQUEST, CONNECT_MQTT_SUCCESS, DISCONNECT_MQTT_FAILURE, DISCONNECT_MQTT_REQUEST, DISCONNECT_MQTT_SUCCESS } from "../constants/mqttConstants"
import mqtt from 'mqtt'
const mqttHost = "host ip address here";
const mqttPort = 8083;
const mqttUrl = `ws://${mqttHost}:${mqttPort}/mqtt`
const mqttOptions = {
keepalive: 30,
protocolId: 'MQTT',
protocolVersion: 4,
clean: true,
reconnectPeriod: 1000,
connectTimeout: 30 * 1000,
clientId: "bharath",
will: {
topic: 'WillMsg',
payload: 'Connection Closed abnormally..!',
qos: 0,
retain: false
},
rejectUnauthorized: false
};
const mqttClient = mqtt.connect(mqttUrl, mqttOptions)
export const mqttConnect = () => async (dispatch) => {
try {
dispatch({
type: CONNECT_MQTT_REQUEST
})
dispatch({
type: CONNECT_MQTT_SUCCESS,
payload: mqttClient
})
//mqttClient.connect()
localStorage.setItem('mqttClient', JSON.stringify(mqttClient))
} catch (error) {
dispatch({
type: CONNECT_MQTT_FAILURE,
payload: error.response && error.response.data.message ? error.response.data.message : error.message
})
}
}
export const mqttDisconnect = () => (dispatch) => {
try {
dispatch({ type: DISCONNECT_MQTT_REQUEST })
mqttClient.end()
localStorage.removeItem('mqttClient')
dispatch({
type: DISCONNECT_MQTT_SUCCESS,
})
} catch (error) {
dispatch({
type: DISCONNECT_MQTT_FAILURE,
payload: error.response && error.response.data.message ? error.response.data.message : error.message
})
}
}
I set up my reducer file like this:
import { CONNECT_MQTT_FAILURE, CONNECT_MQTT_REQUEST, CONNECT_MQTT_SUCCESS, DISCONNECT_MQTT_FAILURE, DISCONNECT_MQTT_REQUEST, DISCONNECT_MQTT_SUCCESS } from "../constants/mqttConstants"
export const connectMqttReducer = (state = {}, action) => {
switch (action.type) {
case CONNECT_MQTT_REQUEST:
return { status: 'connecting' }
case CONNECT_MQTT_SUCCESS:
return { status: 'connected', client: action.payload }
case CONNECT_MQTT_FAILURE:
return { status: 'connect', error: action.payload }
default:
return state
}
}
export const disconnectMqttReducer = (state = {}, action) => {
switch (action.type) {
case DISCONNECT_MQTT_REQUEST:
return { status: 'connected' }
case DISCONNECT_MQTT_SUCCESS:
return { status: 'connect' }
case DISCONNECT_MQTT_FAILURE:
return { status: 'connected', error: action.payload }
default:
return state
}
}
Doing this i'm able to connect but its timestamp when connectedAt is changing continously.And also mqtt.connect() is not function error is also showing. I commented it out. I want to connect it once and disconnect when user login and logout actions are triggered.
Please try the following:
1- Add the following to your environment file:
MQTT_HOST="host ip address here"
MQTT_PORT=8083
2- Add the following in your Constants.js file:
export const mqttUrl = `ws://${process.env.MQTT_HOST}:${process.env.MQTT_PORT}/mqtt`;
export const mqttOptions = {
keepalive: 30,
protocolId: 'MQTT',
protocolVersion: 4,
clean: true,
reconnectPeriod: 1000,
connectTimeout: 30 * 1000,
clientId: 'bharath',
will: {
topic: 'WillMsg',
payload: 'Connection Closed abnormally..!',
qos: 0,
retain: false,
},
rejectUnauthorized: false,
};
export const localStorageKeys = {
mqttClient: 'mqttClient',
};
3- Create a new file which will hold all mqtt functionality /src/clients/MqttClient.js:
import mqtt from 'mqtt';
import { localStorageKeys, mqttOptions, mqttUrl } from '#/js/constants/Helpers';
let instance = null;
class MqttClient {
constructor() {
if (!instance) {
instance = this;
}
return instance;
}
myMqtt;
connect() {
this.myMqtt = mqtt.connect(mqttUrl, mqttOptions);
return new Promise((resolve, reject) => {
this.myMqtt.on('connect', () => {
//add instance to local storage if it's not present (if you need it)
const localStorageMqtt = localStorage.getItem(localStorageKeys.mqttClient);
if (localStorageMqtt === null) {
localStorage.setItem(localStorageKeys.mqttClient, JSON.stringify(this.myMqtt));
}
resolve();
});
this.myMqtt.on('error', (error) => reject(error));
});
}
disconnect() {
return new Promise((resolve) => {
this.myMqtt.end(false, {}, () => {
this.myMqtt = null;
//if you added it to the localstorage (on connect)
localStorage.removeItem(localStorageKeys.mqttClient);
resolve();
});
});
}
subscribe(event) {
return new Promise((resolve, reject) => {
if (!this.myMqtt) return reject('No mqtt connection.');
return this.myMqtt.subscribe(event, (err) => {
// Optional callback that you can use to detect if there's an error
if (err) {
console.error(err);
return reject(err);
}
return resolve();
});
});
}
publish(event, data) {
return new Promise((resolve, reject) => {
if (!this.myMqtt) return reject('No mqtt connection.');
return this.myMqtt.publish(event, data, {}, (err) => {
// Optional callback that you can use to detect if there's an error
if (err) {
console.error(err);
return reject(err);
}
return resolve();
});
});
}
on(event, fun) {
// No promise is needed here, but we're expecting one in the middleware.
return new Promise((resolve, reject) => {
if (!this.myMqtt) return reject('No mqtt connection.');
this.myMqtt.on(event, fun);
resolve();
});
}
}
export default MqttClient;
4- Create a new mqtt middleware in your store directory /src/store/middleWares/MqttMiddleWare.js:
export const mqttMiddleWare =
(mqtt) =>
({ dispatch, getState }) =>
(next) =>
(action) => {
if (typeof action === 'function') {
return action(dispatch, getState);
}
/*
* Mqtt middleware usage.
* promise: (mqtt) => mqtt.connect()
* type: 'mqtt' //always (mqtt)
* types: [REQUEST, SUCCESS, FAILURE]
*/
const { promise, type, types, ...rest } = action;
if (type !== 'mqtt' || !promise) {
// Move on! Not a mqtt request or a badly formed one.
return next(action);
}
const [REQUEST, SUCCESS, FAILURE] = types;
next({ ...rest, type: REQUEST });
return promise({ mqtt, dispatch, getState })
.then((result) => {
return next({ ...rest, result, type: SUCCESS });
})
.catch((error) => {
console.log(error);
return next({ ...rest, error, type: FAILURE });
});
};
5- Update your store config to accept mqtt client as an argument then pass it to the mqtt middleware as follows /src/store/configureStore.js:
const middlewares = [];
// log redux data in development mode only
if (process.env.NODE_ENV !== 'production') {
const { logger } = require('redux-logger');
middlewares.push(logger);
}
const configureStore = (mqttClient) => {
const store = createStore(
rootReducer,
/* preloadedState, */
composeWithDevTools(
applyMiddleware(thunkMiddleware, mqttMiddleWare(mqttClient), ...middlewares)
)
);
return store;
};
export default configureStore;
6- Instantiate your mqtt client in /src/index.jsx and pass it to your store:
const mqttClient = new MqttClient();
const store = configureStore(mqttClient);
7- Update your reducer as follows:
import { CONNECT_MQTT_FAILURE, CONNECT_MQTT_REQUEST, CONNECT_MQTT_SUCCESS, DISCONNECT_MQTT_FAILURE, DISCONNECT_MQTT_REQUEST, DISCONNECT_MQTT_SUCCESS } from "../constants/mqttConstants"
export const connectMqttReducer = (state = {}, action) => {
switch (action.type) {
case CONNECT_MQTT_REQUEST:
return { connectionStatus: 'connecting' }
case CONNECT_MQTT_SUCCESS:
return { connectionStatus: 'connected' }
case CONNECT_MQTT_FAILURE:
return { connectionStatus: 'connect failed', error: action.error }
default:
return state
}
}
export const disconnectMqttReducer = (state = {}, action) => {
switch (action.type) {
case DISCONNECT_MQTT_REQUEST:
return { disconnectionStatus: 'disconnecting' }
case DISCONNECT_MQTT_SUCCESS:
return { disconnectionStatus: 'disconnected' }
case DISCONNECT_MQTT_FAILURE:
return { disconnectionStatus: 'connect failed', error: action.error }
default:
return state
}
}
8- Update your actions as follows:
Connect action:
export const startMqttConnection = () => ({
type: 'mqtt',
types: [CONNECT_MQTT_REQUEST, CONNECT_MQTT_SUCCESS, CONNECT_MQTT_FAILURE],
promise: ({ mqtt }) => mqtt.connect(),
});
Disconnect action:
export const stopMqttConnection = () => ({
type: 'mqtt',
types: [DISCONNECT_MQTT_REQUEST, DISCONNECT_MQTT_SUCCESS, DISCONNECT_MQTT_FAILURE],
promise: ({ mqtt }) => mqtt.disconnect(),
});
9- dispatch the required action as follows:
useEffect(() => {
dispatch(startMqttConnection());
return () => {
if (connectionStatus === 'connected') {
dispatch(stopMqttConnection());
}
};
//eslint-disable-next-line
}, [dispatch]);
Libraries used: redux and redux-saga.
On one of my components I have the useEffect hook that has the dependency set to the status of an API request. That useEffect is then triggering a toast notification based on whether the API request is successful or failed.
But, this useEffect is not firing on each yield put called by the redux-saga defined below.
My intention is the following:
Fire the useEffect in the component after the yield put requestSuccessful(...) or yield put requestFailed(...)
After that, fire the useEffect once again after the yield put initResponseFlags(...)
What's happening currently is that my useEffect is not called at all. I'm assuming it's probably because the yield(s) inside the saga change the redux state so fast (from false to true and then false again) that useEffect is not being able to catch the change.
Places.js (component)
const { places, message, waiting, success, error } = useSelector(state => ({
places: state.Places.data.places,
message: state.Places.requestStatus.message,
waiting: state.Places.requestStatus.waiting,
success: state.Places.requestStatus.success,
error: state.Places.requestStatus.error,
}));
...
useEffect(() => {
console.log("useEffect called");
if (success || error) {
// ... toast message ...
console.log("Firing");
}
}, [dispatch, success, error, message, waiting]);
My project uses the redux-saga library and it contains a generic saga for each API request being made in the app.
saga.js
function* requestStart(args, params) {
if (!params || !params.payload || !params.payload.action)
throw Object.assign(
new Error(`Get action params and payload have not been defined!`),
{ code: 400 }
);
let action = params.payload.action;
let actionPayload = params.payload.actionPayload;
let actions = params.payload.actions;
try {
if (process.env.REACT_APP_API_URL) {
if (actions?.beforeStart) {
yield put(putAction(actions?.beforeStart));
}
const { response, error } = yield call(action, actionPayload);
if (response !== undefined) {
yield put(requestSuccessful(args.namespace, response));
if (actions?.onSuccess) {
yield put(putAction(actions?.onSuccess, response));
}
} else {
yield put(requestFailed(args.namespace, error));
if (actions?.onFailure) {
yield put(putAction(actions?.onFailure, error));
}
}
}
} catch (error) {
yield put(requestFailed(args.namespace, error));
if (args.actions?.onFailure) {
yield put(putAction(params.actions?.onFailure, error));
}
} finally {
yield put(initResponseFlags(args.namespace));
}
}
actions.js
export const initResponseFlags = (namespace) => {
return {
type: `${namespace}/${INIT_RESPONSE_FLAGS}`,
};
};
export const requestStart = (namespace, payload) => {
return {
type: `${namespace}/${REQUEST_START}`,
payload: payload,
};
};
export const requestSuccessful = (namespace, payload) => {
return {
type: `${namespace}/${REQUEST_SUCCESSFUL}`,
payload: payload
};
};
export const requestFailed = (namespace, error) => {
return {
type: `${namespace}/${REQUEST_FAILED}`,
payload: error
};
};
reducer.js
import {
INIT_RESPONSE_FLAGS,
REQUEST_START,
REQUEST_SUCCESSFUL,
REQUEST_FAILED,
} from "./actionTypes";
const initialState = {
message: null,
waiting: false,
success: false,
error: false,
};
const RequestStatus = (namespace) => (state = initialState, action) => {
switch (action.type) {
case `${namespace}/${INIT_RESPONSE_FLAGS}`:
state = {
...state,
message: null,
waiting: false,
success: false,
error: false,
};
break;
case `${namespace}/${REQUEST_START}`:
state = {
...state,
waiting: true,
};
break;
case `${namespace}/${REQUEST_SUCCESSFUL}`:
state = {
...state,
waiting: false,
success: true,
error: false,
};
break;
case `${namespace}/${REQUEST_FAILED}`:
state = {
...state,
waiting: false,
message: action.payload,
success: false,
error: true
};
break;
default: break;
}
return state;
};
export default RequestStatus;
EDIT (12.10.2022. 11:08)
I've just inserted a yield delay(1); of 1ms before my yield put(initResponseFlags(...)); and it works now.
Alas, if there's some other solution (cause this seems like it's botched) - any help would be appreciated!
saga.js
function* requestStart(args, params) {
if (!params || !params.payload || !params.payload.action)
throw Object.assign(
new Error(`Get action params and payload have not been defined!`),
{ code: 400 }
);
let action = params.payload.action;
let actionPayload = params.payload.actionPayload;
let actions = params.payload.actions;
try {
if (process.env.REACT_APP_API_URL) {
if (actions?.beforeStart) {
yield put(putAction(actions?.beforeStart));
}
const { response, error } = yield call(action, actionPayload);
if (response !== undefined) {
console.log('kitica');
yield put(requestSuccessful(args.namespace, response));
if (actions?.onSuccess) {
yield put(putAction(actions?.onSuccess, response));
}
} else {
yield put(requestFailed(args.namespace, error));
if (actions?.onFailure) {
yield put(putAction(actions?.onFailure, error));
}
}
}
} catch (error) {
yield put(requestFailed(args.namespace, error));
if (args.actions?.onFailure) {
yield put(putAction(params.actions?.onFailure, error));
}
} finally {
yield delay(1);
yield put(initResponseFlags(args.namespace));
}
}
I have some component with a code like this:
const startLogin = (code) => {
dispatch(login({ code }));
const publicKeyFromLocalST = window.localStorage.getItem('push_public_key');
setPublicKey(publicKeyFromLocalST);
// etc
When I dispatch the saga login it will store some data in localStorage.
I need to execute the 3rd line (setPublicKey) after that data be actually indeed in localStorage.
How can "await" for dispatch(login({ code })); to be completed before setPublicKey?
Two options:
Execute the setPublicKey function inside the worker saga, you can control the workflow in the worker saga easily with yield.
function* login(action) {
const response = yield call(apiCall);
if (response.error) {
yield put({ type: actionType.LOGIN_FAIL });
} else {
yield put({ type: actionType.LOGIN_SUCCESS, data: response.data });
const publicKeyFromLocalST = window.localStorage.getItem('push_public_key');
setPublicKey(publicKeyFromLocalST);
}
}
Promisify the dispatch(login({code})), you should create a helper function like this:
const loginAsyncCreator = (dispatch) => (payload) => {
return new Promise((resolve, reject) => dispatch(loginCreator(payload, { resolve, reject })));
};
You need to pass the resolve/reject to worker saga via action.meta, then you can decide when to resolve or reject the promise. Then, you can use async/await in your event handler. See below example:
import { call, put, takeLatest } from 'redux-saga/effects';
import { createStoreWithSaga } from '../../utils';
const actionType = {
LOGIN: 'LOGIN',
LOGIN_FAIL: 'LOGIN_FAIL',
LOGIN_SUCCESS: 'LOGIN_SUCCESS',
};
function apiCall() {
return new Promise((resolve) => {
setTimeout(() => {
resolve({ error: null, data: 'login success' });
}, 2000);
});
}
function* login(action) {
console.log('action: ', action);
const {
meta: { resolve, reject },
} = action;
const response = yield call(apiCall);
console.log('response: ', response);
if (response.error) {
yield put({ type: actionType.LOGIN_FAIL });
yield call(reject, response.error);
} else {
yield put({ type: actionType.LOGIN_SUCCESS, data: response.data });
yield call(resolve, response.data);
}
}
function* watchLogin() {
yield takeLatest(actionType.LOGIN, login);
}
const store = createStoreWithSaga(watchLogin);
function loginCreator(payload, meta) {
return {
type: actionType.LOGIN,
payload,
meta,
};
}
const loginAsyncCreator = (dispatch) => (payload) => {
return new Promise((resolve, reject) => dispatch(loginCreator(payload, { resolve, reject })));
};
const loginAsync = loginAsyncCreator(store.dispatch);
async function startLogin() {
await loginAsync({ code: '1' });
console.log('setPublicKey');
}
startLogin();
The logs:
action: {
type: 'LOGIN',
payload: { code: '1' },
meta: { resolve: [Function (anonymous)], reject: [Function (anonymous)] }
}
response: { error: null, data: 'login success' }
setPublicKey
I'm trying to test a useFetch custom hook. This is the hook:
import React from 'react';
function fetchReducer(state, action) {
if (action.type === `fetch`) {
return {
...state,
loading: true,
};
} else if (action.type === `success`) {
return {
data: action.data,
error: null,
loading: false,
};
} else if (action.type === `error`) {
return {
...state,
error: action.error,
loading: false,
};
} else {
throw new Error(
`Hello! This function doesn't support the action you're trying to do.`
);
}
}
export default function useFetch(url, options) {
const [state, dispatch] = React.useReducer(fetchReducer, {
data: null,
error: null,
loading: true,
});
React.useEffect(() => {
dispatch({ type: 'fetch' });
fetch(url, options)
.then((response) => response.json())
.then((data) => dispatch({ type: 'success', data }))
.catch((error) => {
dispatch({ type: 'error', error });
});
}, [url, options]);
return {
loading: state.loading,
data: state.data,
error: state.error,
};
}
This is the test
import useFetch from "./useFetch";
import { renderHook } from "#testing-library/react-hooks";
import { server, rest } from "../mocks/server";
function getAPIbegin() {
return renderHook(() =>
useFetch(
"http://fe-interview-api-dev.ap-southeast-2.elasticbeanstalk.com/api/begin",
{ method: "GET" },
1
)
);
}
test("fetch should return the right data", async () => {
const { result, waitForNextUpdate } = getAPIbegin();
expect(result.current.loading).toBe(true);
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
const response = result.current.data.question;
expect(response.answers[2]).toBe("i think so");
});
// Overwrite mock with failure case
test("shows server error if the request fails", async () => {
server.use(
rest.get(
"http://fe-interview-api-dev.ap-southeast-2.elasticbeanstalk.com/api/begin",
async (req, res, ctx) => {
return res(ctx.status(500));
}
)
);
const { result, waitForNextUpdate } = getAPIbegin();
expect(result.current.loading).toBe(true);
expect(result.current.error).toBe(null);
expect(result.current.data).toBe(null);
await waitForNextUpdate();
console.log(result.current);
expect(result.current.loading).toBe(false);
expect(result.current.error).not.toBe(null);
expect(result.current.data).toBe(null);
});
I keep getting an error only when running the test:
"Warning: Maximum update depth exceeded. This can happen when a component calls setState inside useEffect, but useEffect either doesn't have a dependency array, or one of the dependencies changes on every render."
The error is coming from TestHook: node_modules/#testing-library/react-hooks/lib/index.js:21:23)
at Suspense
I can't figure out how to fix this. URL and options have to be in the dependency array, and running the useEffect doesn't change them, so I don't get why it's causing this loop. When I took them out of the array, the test worked, but I need the effect to run again when those things change.
Any ideas?
Try this.
function getAPIbegin(url, options) {
return renderHook(() =>
useFetch(url, options)
);
}
test("fetch should return the right data", async () => {
const url = "http://fe-interview-api-dev.ap-southeast-2.elasticbeanstalk.com/api/begin";
const options = { method: "GET" };
const { result, waitForNextUpdate } = getAPIbegin(url, options);
expect(result.current.loading).toBe(true);
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
const response = result.current.data.question;
expect(response.answers[2]).toBe("i think so");
});
I haven't used react-hooks-testing-library, but my guess is that whenever React is rendered, the callback send to RenderHook will be called repeatedly, causing different options to be passed in each time.
I have the following redux-sagas:
import { all, call, fork, put, takeEvery } from "redux-saga/effects";
import { catalogs } from 'backend/Catalogs';
import {
ON_FETCH_CATALOGS,
ON_CRUD_POPULATE_LIST,
ON_CRUD_FETCH_NEXT_PAGE,
ON_CRUD_FETCH_PREVIOUS_PAGE,
ON_CRUD_FETCH_PAGE,
ON_CRUD_CREATE,
ON_CRUD_DELETE,
ON_CRUD_REFRESH_PAGE,
ON_CATALOG_POPULATE_OPTIONS,
ON_CRUD_UPDATE,
ON_CRUD_FETCH_LIST,
ON_CRUD_FETCH_RECORD,
GET_TAGS,
ON_FETCH_AUTOMATS,
} from "constants/ActionTypes";
import {
fetchCatalogsSuccess,
showCatalogsMessage,
crudPopulateListSuccess,
crudFetchNextPageSuccess,
crudFetchPreviousPageSuccess,
crudFetchPageSuccess,
crudRefreshPage,
crudRefreshPageSuccess,
catalogPopulateOptionsSuccess,
crudFetchListSuccess,
crudFetchRecordSuccess,
ListTagsSuccess,
fetchAutomatsSuccess,
} from 'actions/Catalogs';
import { ALERT_ERROR ,ALERT_SUCCESS } from 'attractora/AttrAlert';
...
/// fetchAutomats
const fetchAutomatsRequest = async () => {
return await catalogs.fetchAutomats()
.then (automats => automats)
.catch (error => error)
}
function* fetchAutomatsFromRequest ({payload}) {
try {
const automats = yield call(fetchAutomatsRequest);
if (automats.message) {
yield put(showCatalogsMessage(ALERT_ERROR, automats.message));
} else {
yield put(fetchAutomatsSuccess(automats));
}
} catch (error) {
yield put(showCatalogsMessage(ALERT_ERROR, error));
}
}
export function* fetchAutomats() {
yield takeEvery(ON_FETCH_AUTOMATS, fetchAutomatsFromRequest);
}
/// rootSaga
export default function* rootSaga() {
yield all([
fork(fetchCatalogsList),
fork(crudPopulateList),
fork(crudFetchNextPage),
fork(crudFetchPreviousPage),
fork(crudFetchPage),
fork(crudCreateRecord),
fork(crudUpdateRecord),
fork(crudDeleteRecord),
fork(crudSagaRefreshPage),
fork(catalogPopulateOptions),
fork(crudFetchList),
fork(crudFetchRecord),
fork(crudPopulateListTags),
fork(fetchAutomats),
]);
}
And this backend.js file:
export const fetchAutomats = () => {
var requestString = backendServer + 'api/general/automats_for_form/'
axios.get(requestString, getAuthHeader())
.then((Response) => {
return { automats: Response.data, message: null };
})
.catch((Error) => {
return getErrorMessage(Error);
})
}
export const catalogs = {
getCatalogs: getCatalogs,
populateList: populateList,
fetchNextPage: fetchNextPage,
fetchPreviousPage: fetchPreviousPage,
fetchPage: fetchPage,
createRecord: createRecord,
deleteRecord: deleteRecord,
refreshPage: refreshPage,
getList: getList,
updateRecord: updateRecord,
fetchList: fetchList,
fetchRecord: fetchRecord,
populateListTags: populateListTags,
fetchAutomats: fetchAutomats,
searchRepositoryByName,
};
For some reason, line return await catalogs.fetchAutomats() rises the following error: TypeError: Cannot read property 'then' of undefined at fetchAutomatsRequest.
I cannot find where my error lies.
The issue is within the fetchAutomats method, you need to return the promise from the method:
export const fetchAutomats = () => {
var requestString = backendServer + 'api/general/automats_for_form/'
return axios.get(requestString, getAuthHeader())
.then((Response) => {
return { automats: Response.data, message: null };
})
.catch((Error) => {
return getErrorMessage(Error);
})
}