I am trying to access one of the properties of a nested object in a pinia state called activeTicket but it always returns it as undefined but if it is full why could this be ?
export const useTicketStore = defineStore('ticketStore', () => {
const activeTicket = ref({});
const getCurrent = computed(() => {
const formatedCurrent = {
item :activeTicket.value.item,
tipo :activeTicket.value.type,
estado :activeTicket.value.status,
solicitante :activeTicket.value.sendBy.nickName,
fecha :activeTicket.value.createdAt
}
return formatedCurrent
});
return {
currentTicket: activeTicket,
getCurrent
}
});
when commenting on the line
// requester :activeTicket.value.sendBy.nickName,
the error disappears
this is the store
and this is the error i got
ticketStore.js?t=1662253680543:89 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'nickName')
at ReactiveEffect.fn (ticketStore.js?t=1662253680543:89:46)
at ReactiveEffect.run (reactivity.esm-bundler.js:185:25)
at get value [as value] (reactivity.esm-bundler.js:1144:39)
at Object.get2 [as get] (reactivity.esm-bundler.js:484:67)
at Proxy._sfc_render (TechHome.vue:5:34)
at renderComponentRoot (runtime-core.esm-bundler.js:896:44)
at ReactiveEffect.componentUpdateFn [as fn] (runtime-core.esm-bundler.js:5580:57)
at ReactiveEffect.run (reactivity.esm-bundler.js:185:25)
at instance.update (runtime-core.esm-bundler.js:5694:56)
at setupRenderEffect (runtime-core.esm-bundler.js:5708:9)
Related
I'm currently working on the sign in component portion of my app. It requires the user to sign in with their email and password. It has firebase incoporated on the back end. I've been using redux toolkit for a bulk of the app. However, I'm having trouble with createAction and trying to pass the payload in sucessfully. I also wanted to note that i'm doing the async actions via sagas. Could anyone tell me what I'm doing wrong? I provided the error in the console log:
export const emailSignInStart = createAction(
"user/EmailSignInStart",
({ email, password }) => ({
payload: {
email,
password
}
})
);
export function* getSnapShotFromUserAuth(userAuth, additionalDetails) {
try {
const userSnapshot = yield call(
createUserDocumentFromAuth,
userAuth,
additionalDetails
);
yield put(signInSuccess({ id: userSnapshot.id, ...userSnapshot.data() }));
} catch (error) {
yield put(signInFailure(error));
}
}
export function* EmailSignIn({ payload: { email, password } }) {
try {
const { user } = yield call(
signInAuthUserWithEmailAndPassword,
email,
password
);
yield call(getSnapShotFromUserAuth, user);
} catch (error) {
yield put(signInFailure(error));
}
}
Result in console:
payload
:
TypeError: Cannot read properties of undefined (reading 'user') at eval (https://pyluef.csb.app/src/sagas/user/user.saga.js:67:29) at Generator.next (<anonymous>) at next (https://pyluef.csb.app/node_modules/#redux-saga/core/dist/redux-saga-core.dev.cjs.js:1161:27) at currCb (https://pyluef.csb.app/node_modules/#redux-saga/core/dist/redux-saga-core.dev.cjs.js:1255:7)
message
:
"Cannot read properties of undefined (reading 'user')"
stack
:
"TypeError: Cannot read properties of undefined (reading 'user')\n at eval (https://pyluef.csb.app/src/sagas/user/user.saga.js:67:29)\n at Generator.next (<anonymous>)\n at next (https://pyluef.csb.app/node_modules/#redux-saga/core/dist/redux-saga-core.dev.cjs.js:1161:27)\n at currCb (https://pyluef.csb.app/node_modules/#redux-saga/core/dist/redux-saga-core.dev.cjs.js:1255:7)"
[[Prototype]]
:
Error
type
:
"user/signInFailure"
##redux-saga/SAGA_ACTION
:
true
The code I used without using Redux toolkit. It worked this way:
export const USER_ACTION_TYPES = {
EMAIL_SIGN_IN_START: "user/EMAIL_SIGN_IN_START"
};
export const createAction = (type, payload) => ({ type, payload });
export const emailSignInStart = (email, password) =>
createAction(USER_ACTION_TYPES.EMAIL_SIGN_IN_START, { email, password });
I'm fairly new to graphql/apollo setup, and am stuck on the following issue:
My setup looks like this roughly:
Resolvers:
export const resolvers: Resolvers = {
Query: {
getUser: withApiAuthRequired(getUser)
}
};
async function getUser(req: any, res: any) {
try {
const { accessToken } = await getAccessToken(req, res);
console.log(accessToken);
} catch (error) {
console.error(error);
res.status(error.status || 500).end(error.message);
}
}
Client caller:
const data = await client.query({
query: gql`
query UsersQuery {
getUser
}
`
});
console.log(data);
The error I get:
Uncaught (in promise) Error: Request is not available
at new ApolloError (index.js?f0e4:29:1)
at eval (QueryManager.js?2692:596:1)
at both (asyncMap.js?bd9c:16:46)
at eval (asyncMap.js?bd9c:9:57)
at new Promise (<anonymous>)
at Object.then (asyncMap.js?bd9c:9:1)
at Object.eval [as next] (asyncMap.js?bd9c:17:1)
at notifySubscription (module.js?9653:132:1)
at onNotify (module.js?9653:176:1)
at SubscriptionObserver.next (module.js?9653:225:1)
at eval (iteration.js?aad9:4:50)
at Array.forEach (<anonymous>)
at iterateObserversSafely (iteration.js?aad9:4:1)
at Object.next (Concast.js?eb39:25:43)
at notifySubscription (module.js?9653:132:1)
at onNotify (module.js?9653:176:1)
at SubscriptionObserver.next (module.js?9653:225:1)
at eval (createHttpLink.js?2d67:103:1)
Thank you so much for the guidance!
try this one:
const data = await client.query({
query: gql `
query {
getUser
}
`
});
console.log(data);
I believe the issue is that I was trying to use withApiAuthRequired inside Resolvers. The argument to Resolvers needs to be an unwrapped function to work. I ended up just skipping the withApiAuthRequired wrapper and using getSession instead.
I'm trying to create a new document under the collection "accounts" (this is working), and then add the ID of the newly created account to an array of accounts the current user has access to (array is called accountAccess). Here's the function:
async function addAccount(accountName, id) {
await db.collection('accounts').add({
name: accountName,
owner: id
}).then(async (account) => {
const accountIdToAdd = db.FieldValue.arrayUnion(account.id);
await db.collection('users').doc(userId).update({
accountAccess: accountIdToAdd,
});
});
}
But I receive the error `[Unhandled promise rejection: TypeError: undefined is not an object (evaluating '_firebase.db.FieldValue.arrayUnion')]
Any ideas what I'm doing wrong in the then block?
I am following an udemy course to learn redux coding on codePen, however, I got this following error.
redux.min.js:1 Uncaught TypeError: Cannot read property 'name' of undefined
at policies (pen.js:61)
at redux.min.js:1
at Array.forEach (<anonymous>)
at redux.min.js:1
at e.combineReducers (redux.min.js:1)
at pen.js:73
it tells me that it is because the name from the policies reducer function could not read the action.payload.name because it's undefined. I did not see the instructor have the same problem, but I have faithfully checked my code and it's identical to his. I just can't understand how I can fix it to display the state correctly.
I have debugged and tried to fix the problem, but so far the code keeps throwing error unless I delete the action.payload.name from the policies reducer function.
console.clear();
// people dropping off a form (Aaction Creator)
const createPolicy =(name, amount)=>{
// console.log(name,amount,'test createpolicy')
return { // Action (a form in our analogy)
type:'CREATE_POLICY',
payload: {
name:name,
amount: amount
}
};
};
const deletePolicy = (name) =>{
return {
type:'DELETE_POLICY',
payload:{
name: name
}
}
}
const createClaim = (name, amountOfMoneyToCollect) =>{
return {
type:'CREATE_CLAIM',
payload:{
name: name,
amountOfMoneyToCollect: amountOfMoneyToCollect
}
};
};
// Reducers (Departments!)
// default oldListOfClaims=[] is for initial state.
const claimsHistory=(oldListOfClaims=[], action)=>{
if(action.type==="CREATE_CLAIM"){
// we care about this action (FORM!)
return [...oldListOfClaims, action.payload];
}
// we don't care the action (FORM!)
return oldListOfClaims;
};
const accounting=(bagOfMoney=100, action)=>{
if(action.type==='CREATE_CLAIM'){
return bagOfMoney - action.amountOfMoneyToCollect;
}
else if(action.type==='CREATE_POLICY'){
return bagOfMoney + action.payload.amount;
}
return bagOfMoney;
}
const policies = ( listOfPolicies = [], action)=>{
if(action.type = 'CREATE_POLICY'){
console.log( action.payload,'test playload name')
return [...listOfPolicies,action.payload.name]
}
else if(action.type='DELETE_POLICY'){
return listOfPolicies.filter(name =>
name!==action.payload.name);
}
return listOfPolicies;
};
const { createStore, combineReducers} = Redux;
const ourDepartments = combineReducers ({
accounting: accounting,
claimsHistory: claimsHistory,
policies: policies
})
const store = createStore(ourDepartments);
console.log(store)
store.dispatch(createPolicy('Alex', 20));
store.dispatch(createPolicy('Jim', 30));
store.dispatch(createPolicy('Bob', 40));
console.log(store.getState());
I would expect to see the console.log of the current state after the new names and amounts are dispatched to the store. and figure out why this error keeps occurring.
Review your policies reducer - you are assigning rather than comparing against action types when checking against your types. Update it to the code below:
const policies = ( listOfPolicies = [], action)=>{
// previously if(action.type = 'CREATE_POLICY'){
if(action.type === 'CREATE_POLICY'){
console.log( action.payload,'test playload name')
return [...listOfPolicies,action.payload.name]
}
// previously else if(action.type='DELETE_POLICY'){
else if(action.type==='DELETE_POLICY'){
return listOfPolicies.filter(name =>
name!==action.payload.name);
}
return listOfPolicies;
};
I write application in React an Redux and I have a case that I have to send request to some resource when specific action was called and response of type 'text/html' write to state. This resource can return status 200 or 404, and I cannot write correct test for case with response 404.
To run tests I use jest library.
Action.js:
export const actions = {
GET_RESOURCE_SUCCESS: 'GET_RESOURCE_SUCCESS',
GET_RESOURCE_FAILURE: 'GET_RESOURCE_FAILURE'
};
export const getResourceSuccess = (response) => ({
type: actions.GET_RESOURCE_SUCCESS,
payload: response
});
export const getResourceFailure = () => ({
type: actions.GET_RESOURCE_FAILURE
});
Reducer.js:
import { handleActions } from 'redux-actions';
import { actions } from './Action';
const initialState = {
content: ''
};
export const getResourceReducer = handleActions(
{
[actions.GET_RESOURCE_SUCCESS]: (state, action) => ({ ...state, content: action.payload })
},
{
[actions.GET_RESOURCE_FAILURE]: () => ({ initialState })
},
initialState
);
In brief: when resource returns status 200 and content exists I want to overwrite content from initialState and call action GET_RESOURCE_SUCCESS, when resource returns status 404 and content doesn't exist I want not to overwrite the content and call action GET_RESOURCE_FAILURE.
GetResourceEpic.js:
import { ajax } from 'rxjs/observable/dom/ajax';
import { combineEpics } from 'redux-observable';
import { Observable } from 'rxjs';
import { getResourceSuccess, getResourceFailure } from '../Action';
const specificActionTypes = [
'SPECIFIC_ACTION_ONE',
'SPECIFIC_ACTION_TWO'
];
const getResource = () => ajax({
method: 'GET',
url: 'http://example.com',
headers: {
Accept: 'text/html'
},
crossDomain: true,
responseType: 'text/html'
});
const getResourceEpic = (action$, store) => action$
.filter(action => specificActionTypes.includes(action.type))
.flatMap(() => getResource()
// when response has status 200 and field response call getResourceSuccess
.map(({ response }) => getResourceSuccess(response))
// when response has status 404 and doesn't have field response call getResourceFailure
.catch(() => {
// helper statement to show in browser that the .catch() was called
console.log('Error');
return getResourceFailure();
})
);
export default combineEpics(
getResourceEpic
);
And it works in generally, but I get two errors:
first:
Uncaught TypeError: You provided an invalid object where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.
at Object.subscribeToResult (subscribeToResult.js:73)
at CatchSubscriber../node_modules/rxjs/operator/catch.js.CatchSubscriber.error (catch.js:111)
at MapSubscriber../node_modules/rxjs/Subscriber.js.Subscriber._error (Subscriber.js:128)
at MapSubscriber../node_modules/rxjs/Subscriber.js.Subscriber.error (Subscriber.js:102)
at AjaxSubscriber../node_modules/rxjs/Subscriber.js.Subscriber._error (Subscriber.js:128)
at AjaxSubscriber../node_modules/rxjs/Subscriber.js.Subscriber.error (Subscriber.js:102)
at XMLHttpRequest.xhrReadyStateChange (AjaxObservable.js:327)
at XMLHttpRequest.d (raven.js:363)
and second:
Could not consume error: TypeError: Cannot read property 'length' of null
at getLinesAround (http://localhost:3000/static/js/bundle.js:47197:74)
at http://localhost:3000/static/js/bundle.js:47537:402
at Array.map (native)
at _callee2$ (http://localhost:3000/static/js/bundle.js:47517:54)
at tryCatch (http://localhost:3000/static/js/bundle.js:58220:40)
at Generator.invoke [as _invoke] (http://localhost:3000/static/js/bundle.js:58458:22)
at Generator.prototype.(anonymous function) [as next] (http://localhost:3000/static/js/bundle.js:58272:21)
at step (http://localhost:3000/static/js/bundle.js:47553:191)
at http://localhost:3000/static/js/bundle.js:47553:361
raven.js:51
And mentioned above problems don't allow me to write a tests, because only responses with status 200 pass the tests, other throws errors.
it('should dispatch GET_RESOURCE_SUCCESS when SPECIFIC_ACTION_ONE was dispatched', async () => {
store = mockStore();
const response = 'some content';
nock('http://example.com')
.get('/')
.reply(200, response);
const payload = { type: 'SPECIFIC_ACTION_ONE' };
// specificActionOne() produces and action of type 'SPECFIC_ACTION_ONE'
const action$ = ActionsObservable.of(specificActionOne(payload));
const resultAction = await getResourceEpic(action$, store).toPromise();
expect(resultAction)
.toEqual(getResourceSuccess(response));
});
And test above pass, but case with status equal to 404 doesn't pass:
it('should dispatch GET_RESOURCE_FAILURE when SPECIFIC_ACTION_ONE was dispatched', async () => {
store = mockStore();
nock('http://example.com')
.get('/')
.reply(404);
const payload = { type: 'SPECIFIC_ACTION_ONE' };
const action$ = ActionsObservable.of(specificActionOne(payload));
const resultAction = await getResourceEpic(action$, store).toPromise();
expect(resultAction)
.toEqual(getResourceFailure());
});
And test above doesn't pass and I get the result:
TypeError: You provided an invalid object where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.
at Object.subscribeToResult (node_modules/rxjs/util/subscribeToResult.js:73:27)
at CatchSubscriber.Object.<anonymous>.CatchSubscriber.error (node_modules/rxjs/operator/catch.js:111:42)
at MapSubscriber.Object.<anonymous>.Subscriber._error (node_modules/rxjs/Subscriber.js:128:26)
at MapSubscriber.Object.<anonymous>.Subscriber.error (node_modules/rxjs/Subscriber.js:102:18)
at AjaxSubscriber.Object.<anonymous>.Subscriber._error (node_modules/rxjs/Subscriber.js:128:26)
at AjaxSubscriber.Object.<anonymous>.Subscriber.error (node_modules/rxjs/Subscriber.js:102:18)
at XMLHttpRequest.xhrReadyStateChange [as onreadystatechange] (node_modules/rxjs/observable/dom/AjaxObservable.js:327:32)
at XMLHttpRequest.callback.(anonymous function) (node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:289:32)
at invokeEventListeners (node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:219:27)
at invokeInlineListeners (node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:166:7)
at EventTargetImpl._dispatch (node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:122:7)
at EventTargetImpl.dispatchEvent (node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:87:17)
at XMLHttpRequest.dispatchEvent (node_modules/jsdom/lib/jsdom/living/generated/EventTarget.js:61:35)
at readyStateChange (node_modules/jsdom/lib/jsdom/living/xmlhttprequest.js:829:9)
at Request.properties.client.on (node_modules/jsdom/lib/jsdom/living/xmlhttprequest.js:947:7)
at Request.emit (events.js:132:15)
at IncomingMessage.<anonymous> (node_modules/request/request.js:1085:12)
at Object.onceWrapper (events.js:219:13)
at IncomingMessage.emit (events.js:132:15)
at endReadableNT (_stream_readable.js:1101:12)
at process._tickCallback (internal/process/next_tick.js:114:19)
The function passed to catch has to return an observable. You are returning an action.
Instead, you should do this:
import { of } from 'rxjs/observable/of';
...
.catch(() => {
console.log('Error');
return of(getResourceFailure());
})