react-router-dom push() function not available in asyn/await actions - reactjs

So the title is pretty descriptive, the error i'm getting is:
actions.js:392 Uncaught (in promise) TypeError: (0 , _reactRouterDom.push) is not a function
at _callee6$ (webpack:///./src/app/Army/store/actions.js?:392:49)
at tryCatch (http://localhost:8001/vendor.js:152705:40)
at Generator.invoke [as _invoke] (http://localhost:8001/vendor.js:152943:22)
at Generator.prototype.(anonymous function) [as next] (http://localhost:8001/vendor.js:152757:21)
at step (webpack:///./src/app/Army/store/actions.js?:22:191)
at eval (webpack:///./src/app/Army/store/actions.js?:22:361)
at <anonymous>
Just a bit of background, I'm using import 'babel-polyfill'; to do a asyn/await transpiling and my action looks like this:
export const update = (Id, Data, publish) => async (dispatch) => {
try {
dispatch({
type: BA_UPDATING,
payload: { Id },
});
const lib = await client.then(bfn => bfn);
const response = await lib.getArmy(null, Data.type, Id, { ...Data, publish });
dispatch({
type: BA_UPDATED,
payload: { Id, publish, response },
});
dispatch(push('/Army')); // ERROR.
} catch (error) {
dispatch({
type: BA_ERROR,
payload: {
actions: 'update',
Id,
},
});
}
};
react-router-dom v4.1.1

Related

problems in request in unit test the status is undefined

I am trying to do a unit test to an action in my react application but apparently everything works fine, I get a message that I am not understanding when making the request and the status is undefined, I don't have any specific variable with the status name so I assume it must be a problem when making the promise. How can I solve this problem?
error : undefined | TypeError: Cannot read property 'status' of
undefined
at request (C:\Users\amils\OneDrive\Documentos\Bootcamp - Training\Project\tracking-tool-webapp\src\api\utilities\fetch.js:45:26)
at processTicksAndRejections (internal/process/task_queues.js:95:5)
at Object.getAll (C:\Users\amils\OneDrive\Documentos\Bootcamp -
Training\Project\tracking-tool-webapp\src\api\utilities\provider.js:18:9)
console log result:
console.log
[
{
title: 'Candidates',
errorMessages: [],
candidates: [],
reports: null,
loading: false,
programsInProgress: [],
programVersions: [],
statusType: []
},
{ onLoadCandidates: [Function: onLoadCandidates] }
]
The code:
it('Should get all candidates', async () => {
const mockResponse = {
candidates: [
{
id: '4fffc534-1d83-14d5-b264-1e17f2abd322',
name: 'Homer Simpson',
status: 'InProgress',
},
{
id: '4fffc535-1d83-14d5-b264-1e17f2abd322',
name: 'Junior Santos',
status: 'InProgress',
},
],
};
global.fetch = jest.fn(() => {
Promise.resolve({
status: 200,
json: () => Promise.resolve(mockResponse),
});
});
const result = await customRenderHook();
const actions = result.current[1];
console.log(result);
await act(async () => {
actions.onLoadCandidates();
});
const state = result.current[0];
expect(state.candidates).toEqual(mockResponse);
});
code customRenderHook:
const customRenderHook = () => {
const wrapper = ({ children }) => <CandidatesDataProvider>{children}</CandidatesDataProvider>;
const { result } = renderHook(() => useCandidatesContext(), { wrapper });
return result;
};
I find the problem, currently, I cant execure my promise without a tokes 'Bearer', now the problem here is how can I create a mock of token:
function onLoadCandidates(dispatch) {
dispatch({ type: CandidatesActionTypes.loading, payload: true });
const token = localStorage.getItem('token');
apiCandidate
.getAll(token)
.then((response) => {
dispatch({ type: CandidatesActionTypes.loading, payload: response.data });
})
.catch((err) => {
dispatch({ type: CandidatesActionTypes.Error, payload: err.message });
LoggerService.error(err);
})
.finally(() => {
dispatch({ type: CandidatesActionTypes.loading, payload: false });
});
}
You could mock localStorage.getItem to return a token in the format required by apiCandidate.getAll(token):
localStorage.getItem = jest.fn().mockReturnValue('your-token');

Unhandled Rejection (TypeError): Cannot read properties of undefined (reading 'get')

I am trying to implement PayPal Button on my site, but somehow something is going wrong. I have checked my code over and over. Also researched other potential solutions, but can't get it to work. When I do a get request in Postman I get a nice response.
The error it trows is:
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'get')
In my opinion get is not undefined and I handle the errors correctly.
Image of the error
I have the following code:
Express server.js
app.get('/api/config/paypal', (req, res) =>{
res.send(process.env.PAYPAL_CLIENT_ID || 'sb');
});
OrderScreen.js
export default function OrderScreen(){
const params = useParams();
const { id: orderId } = params;
const [setSdkReady] = useState(false);
...
useEffect(()=> {
const addPaypalScript = async () => {
const { data: clientId } = await Axios.get('/api/config/paypal')
console.log(clientId);
const script = document.createElement('script')
script.type = 'text/javascript'
script.src = `https://www.paypal.com/sdk/js?client-id=${clientId}`
script.async = true
script.onload = () => {
setSdkReady(true)
}
document.body.appendChild(script)
}
if(!order){
dispatch(detailsOrder(orderId))
}else if (!order.isPaid) {
if (!window.paypal) {
addPaypalScript()
} else {
setSdkReady(true)
}
}
}, [dispatch, order, orderId, setSdkReady]);
...
return()
}
In OrderActions.js
export const detailsOrder = (orderId) => async (dispatch, getState) => {
dispatch({ type: ORDER_DETAILS_REQUEST, payload: orderId });
const {
userSignin: { userInfo },
} = getState();
try {
const { data } = await Axios.get(`/api/orders/${orderId}`, {
headers: { Authorization: `Bearer ${userInfo.token}` },
});
dispatch({ type: ORDER_DETAILS_SUCCESS, payload: data });
} catch (error) {
const message =
error.response && error.response.data.message
? error.response.data.message
: error.message;
dispatch({ type: ORDER_DETAILS_FAIL, payload: message });
}
};
Help is much appreciated! Thanks in advance for any help.
You should import axios with:
import axios from 'axios';
And use it like this (lowercased):
const { data: clientId } = await axios.get('/api/config/paypal')

react jest unit test case TypeError: Cannot read property 'then' of undefined

I have write the testcases using react, redux-mock-store and redux, but I keep getting and error. I have checked this same error on stackoverflow but i am unable to understand in my case.
Cannot read property '.then' of undefined when testing async action creators with redux and react
here is my index.js file:
import { post } from '../../../service/index';
import { CREATE_JD_SUCCESS, CREATE_JD_FAILED, CREATE_JD_URL, REQUEST_INITIATED, REQUEST_SUCCESSED } from '../../../constants/AppConstants'
export function createJob(jd) {
return (dispatch) => {
dispatch({
type: REQUEST_INITIATED
});
post(CREATE_JD_URL, jd)
.then((response) => {
if (response.status === 200) {
dispatch({
type: REQUEST_SUCCESSED,
});
dispatch({
type: CREATE_JD_SUCCESS,
data: response.payload,
})
}
else {
dispatch({
type: REQUEST_SUCCESSED
});
dispatch({
type: CREATE_JD_FAILED,
data: response.status,
});
}
})
}
}
here is my index.test.js file
import * as actions from '../index';
import configureMockStore from 'redux-mock-store';
import moxios from 'moxios';
import thunk from 'redux-thunk';
import apiGatewayEndpoint from '../../../../config/index';
import { CREATE_JD_SUCCESS, CREATE_JD_URL } from '../../../../constants/AppConstants';
const middlewares = [thunk];
const mockStore = configureMockStore(middlewares);
const newJd = {
"companyId": "12345",
"jobDescription": 'Hello there'
};
const responseData = "job created!";
describe('actions for creating new job', () => {
beforeEach(function () {
moxios.install();
});
afterEach(function () {
moxios.uninstall();
});
it('action for create job', async (done) => {
let url = CREATE_JD_URL;
moxios.stubRequest(apiGatewayEndpoint.apiGatewayEndpoint + url, {
status: 200,
response: responseData
});
const expectedActions = [{ "type": "REQUEST_INITIATED" }, { "type": "REQUEST_SUCCESSED" }, { data: responseData, type: "CREATE_JD_SUCCESS" }];
const store = mockStore({});
await store.dispatch(actions.createJob(newJd))
.then(() => {
expect(store.getActions()).toEqual(expectedActions);
});
done();
});
});
on the above link in answered he said that error is coming because of store.dispatch() method returning undefined.bt in my case my other actions test cases are running fine which is the same what i have wrote above dont know why getting this error.
console error while running npm test:
● actions for creating new jd › action for create jd
TypeError: Cannot read property 'then' of undefined
38 | const expectedActions = [{ "type": "REQUEST_INITIATED" }, { "type": "REQUEST_SUCCESSED" }, { data: responseData, type: "CREATE_JD_SUCCESS" }];
39 | const store = mockStore({});
> 40 | await store.dispatch(actions.createJob(newJd))
| ^
41 | .then(() => {
42 | expect(store.getActions()).toEqual(expectedActions);
43 | });
if any one know please guide me what I am doing wrong here.any help will be appreciated
just write return before the post calling in your index.js file.
e.g:
return post(CREATE_JD_URL, jd)
.then((response) => {
...
this worked for me.

Apollo client: Error: Network error: nextLink.request is not a function

index.js:2177 Unhandled (in react-apollo:Apollo(App)) Error: Network error: nextLink.request is not a function
at new ApolloError (http://localhost:8000/commons.js:1946:29)
at ObservableQuery../node_modules/apollo-client/bundle.umd.js.ObservableQuery.currentResult (http://localhost:8000/commons.js:2048:25)
at ProxyComponent.GraphQL.dataForChild (http://localhost:8000/commons.js:68056:63)
at ProxyComponent.dataForChild (http://localhost:8000/commons.js:94845:31)
at ProxyComponent.GraphQL.render (http://localhost:8000/commons.js:68106:34)
at ProxyComponent.render (http://localhost:8000/commons.js:94845:31)
at http://localhost:8000/commons.js:73619:22
at measureLifeCyclePerf (http://localhost:8000/commons.js:72899:13)
at ReactCompositeComponentWrapper._renderValidatedComponentWithoutOwnerOrContext (http://localhost:8000/commons.js:73618:26)
at ReactCompositeComponentWrapper._renderValidatedComponent (http://localhost:8000/commons.js:73645:33)
at ReactCompositeComponentWrapper._updateRenderedComponent (http://localhost:8000/commons.js:73569:37)
at ReactCompositeComponentWrapper._performComponentUpdate (http://localhost:8000/commons.js:73547:11)
at ReactCompositeComponentWrapper.updateComponent (http://localhost:8000/commons.js:73468:13)
at ReactCompositeComponentWrapper.performUpdateIfNecessary (http://localhost:8000/commons.js:73384:13)
at Object.performUpdateIfNecessary (http://localhost:8000/commons.js:79624:23)
at runBatchedUpdates (http://localhost:8000/commons.js:80351:22)
at ReactReconcileTransaction.perform (http://localhost:8000/commons.js:82222:21)
at ReactUpdatesFlushTransaction.perform (http://localhost:8000/commons.js:82222:21)
at ReactUpdatesFlushTransaction.perform (http://localhost:8000/commons.js:80290:33)
at Object.flushBatchedUpdates (http://localhost:8000/commons.js:80373:20)
at ReactDefaultBatchingStrategyTransaction.closeAll (http://localhost:8000/commons.js:82288:26)
at ReactDefaultBatchingStrategyTransaction.perform (http://localhost:8000/commons.js:82235:17)
at Object.batchedUpdates (http://localhost:8000/commons.js:77217:27)
at Object.enqueueUpdate (http://localhost:8000/commons.js:80401:23)
at enqueueUpdate (http://localhost:8000/commons.js:79988:17)
at Object.enqueueForceUpdate (http://localhost:8000/commons.js:80120:6)
at ProxyComponent../node_modules/react/lib/ReactBaseClasses.js.ReactComponent.forceUpdate (http://localhost:8000/commons.js:100002:17)
at ProxyComponent.GraphQL.forceRenderChildren (http://localhost:8000/commons.js:68024:27)
at ProxyComponent.forceRenderChildren (http://localhost:8000/commons.js:94845:31)
at next (http://localhost:8000/commons.js:67999:28)
at Object.handleError [as error] (http://localhost:8000/commons.js:68003:33)
at SubscriptionObserver.error (http://localhost:8000/commons.js:105336:21)
at http://localhost:8000/commons.js:2287:83
at Array.forEach (<anonymous>)
at Object.error (http://localhost:8000/commons.js:2287:34)
at http://localhost:8000/commons.js:2829:39
at http://localhost:8000/commons.js:3203:18
at Array.forEach (<anonymous>)
at http://localhost:8000/commons.js:3202:19
at Map.forEach (<anonymous>)
at QueryManager../node_modules/apollo-client/bundle.umd.js.QueryManager.broadcastQueries (http://localhost:8000/commons.js:3197:23)
at http://localhost:8000/commons.js:2771:32
at <anonymous>
I am trying to integrate apollo-link-state into my app and when I try to run a query that hits an external endpoint as well as the cache I get an error...
here is the query and the HOC:
// the graphql query to get the user
const userQuery = gql`
query UserQuery {
getUser(id: 1) {
givenName
avatarUrl
account {
credit
}
}
user #client {
name
}
}
`;
// mapping the results to the props
const mapResultsToProps = ({ data }) => {
console.log(data);
if (!data.getUser) {
return {
name: ''
};
}
console.log('hit');
console.log(data);
return {
name: data.getUser.givenName
};
};
export default graphql(userQuery, { props: mapResultsToProps })(App);
And here is how I am setting everything up:
const cache = new InMemoryCache();
const stateLink = withClientState({
cache,
resolvers: {
Mutation: {
setUser: (_, { name }, { cache }) => {
const data = {
user: {
__typename: 'UserName',
name
}
};
cache.writeData({ data });
}
}
},
defaults: {
user: {
__typename: 'UserName',
name: 'name in local cache'
}
}
});
const httpLink = new HttpLink({
uri: urls.graphqlServer + urls.graphqlEndpoint,
credentials: 'same-origin',
headers: {
authorization: getCookie('Authorization')
}
});
const client = new ApolloClient({
cache,
link: new ApolloLink([stateLink, httpLink]),
connectToDevTools: true
});
window.__APOLLO_CLIENT__ = client;
return (
<ApolloProvider client={client}>
<Root />
</ApolloProvider>
);
Any idea what is going on?
The signature of the constructor of ApolloLink is the following:
constructor(request?: RequestHandler);
If you want to chain several links, you need to use
ApolloLink.from([stateLink, httpLink])
instead.

Dispatch is not defined-ReatcJs

I tried looking for answers from the sources that had same issue, but didnt work for my case.
I'm using this function to get some settings for my application:
js:
export function _someFun() {
setData("abc").then(res => {
dispatch({ type: ACTION.SET_USER_SUCCESS, res });
}, (error) => {
dispatch({ type: ACTION.SET_USER_FAILURE, error });
});
}
where: setData is a function I'm importing from the Api file that basically sends a response to fetch the data. With the above call, its going into the success call but saying: "dispatch is not defined". Not sure how to get this working..any idea???
You need to install first the redux-thunk middleware:
npm install --save redux-thunk
Then, import an actionTypes object from the actionTypes.js file, that stores all the action types. Basically instead of ACTION you should use actionTypes. Is more explicit and clear that way.
And then try this in your action creator file:
export const setUserSuccess = (response) => {
return {
type: actionTypes.SET_USER_SUCCESS,
payload: {
response: response
}
}
};
export const setUserFailure = (error) => {
return {
type: actionTypes.SET_USER_FAILURE,
payload: {
error: error
}
}
};
export const _someFun = () => {
// Using the redux-thunk middleware
return dispatch => {
setData("abc")
.then(response => {
dispatch(setUserSuccess(response));
}).catch(error => {
dispatch(setUserFailure(error));
});
}
};

Resources