Create Action w/ Redux Toolkit; Passing in A Payload - redux

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 });

Related

How to handle next api route using dynamic id

I am using NextJS and created three layers that separate the logic.
The purpose is to minimise the error handling to the getServerSideProps section. I want to get all the lists from the database.
In the first layer, in the API route I created a folder called get-all-lists and a file [userId].js. The get request will be 'http://localhost:3000/api/get-all-lists/iudga937gr8'. Bellow there is the api route that get all the lists with the help of Prsima. It is working perfectly
import prisma from '../../../lib/prisma'
export default async function handler(req, res) {
const { userId } = req.query;
if (req.method === 'GET') {
try {
const shoppingLists = await prisma.List.findMany({ where: { userId: userId }});
res.status(200).json({lists: shoppingLists});
}
catch (error) {
console.log(error);
res.status(500).json({ message: 'Something went wrong. Please try again'});
}
}
else {
res.status(500).json({message: 'Invalid method requested!'});
}
}
The next layer, is the abstraction one which sent the final result to getServerSideProps. I created this because I need to fetch alot of requests and it would be too messy...
export const getAllLists = async userId => {
try {
const lists = await axios.get(`/api/get-all-lists/${userId}`);
return lists;
}
catch (error) {
console.log('Abstraction layer error: ', error);
return 'Something went wrong. Please try again later';
}
}
The problem arise here. In the postman I have the right result. In postman I use http://localhost:3000/api/get-all-lists/clbcpc0hi0002sb1wsiea3q5d and the server sent me the array specified.
But this function does not work and send me this error:
Abstraction layer error: TypeError [ERR_INVALID_URL]: Invalid URL
at new NodeError (node:internal/errors:371:5)
at onParseError (node:internal/url:552:9)
at new URL (node:internal/url:628:5)
at dispatchHttpRequest (file:///Users/sasdaniel/Desktop/massage/node_modules/axios/lib/adapters/http.js:176:20)
at new Promise (<anonymous>)
at http (file:///Users/sasdaniel/Desktop/massage/node_modules/axios/lib/adapters/http.js:112:10)
at Axios.dispatchRequest (file:///Users/sasdaniel/Desktop/massage/node_modules/axios/lib/core/dispatchRequest.js:51:10)
at Axios.request (file:///Users/sasdaniel/Desktop/massage/node_modules/axios/lib/core/Axios.js:142:33)
at Axios.<computed> [as get] (file:///Users/sasdaniel/Desktop/massage/node_modules/axios/lib/core/Axios.js:168:17)
at Function.wrap [as get] (file:///Users/sasdaniel/Desktop/massage/node_modules/axios/lib/helpers/bind.js:5:15) {
input: '/api/get-all-lists/clbcpc0hi0002sb1wsiea3q5d',
code: 'ERR_INVALID_URL'
}
I also tried to paste the localhost in the browser and it have no problem.
You could extract the functionality into /lib/getAllList.js:
import prisma from './prisma';
export default async function getAllLists(userId) {
return await prisma.List.findMany({ where: { userId: userId }});
}
Then use it in your API route:
import getAllLists from '../../../lib/getAllLists';
export default async function handler(req, res) {
const { userId } = req.query;
if (req.method === 'GET') {
try {
const shoppingLists = await getAllLists(userId);
res.status(200).json({lists: shoppingLists});
}
catch (error) {
console.log(error);
res.status(500).json({ message: 'Something went wrong. Please try again'});
}
}
else {
res.status(500).json({message: 'Invalid method requested!'});
}
}
Then use it in getServerSideProps:
import getAllLists from 'path/to/lib/getAllLists';
export async function getServerSideProps(context) {
const { userId } = context.params;
const shoppingLists = await getAllLists(userId);
return {
props: {
shoppingLists,
},
};
}

Signin method with Nextjs and trpc returning resolver is not a function

So im trying to build my register method without re-enventing nothing crazy with the create-t3-app stack with nextjs, trpc and nextauth:
export const signUpRouter = router({
signup: publicProcedure.input(UserModel).mutation(async ({ ctx, input }) => {
debugger;
try {
const { nickname, email, password } = input;
//check duplicate users
const checkingUsers = await ctx.prisma.user.findFirst({
where: {
email,
},
});
if (checkingUsers) {
return { message: "User already exists..." };
}
//hash password
return await ctx.prisma.user.create({
data: {
nickname,
email,
password: await hash(password, 12),
},
});
} catch (error: any) {
console.log("error", error);
throw new Error(error);
}
}),
});
export default signUpRouter;
This file is inside pages/api/auth/signup.ts
Should I have this on the server part ?
I have the router on my appRouter file
export const appRouter = router({
userLogin: userLoginRouter,
auth: authRouter,
signin: signInRouter,
signup: signUpRouter,
});
And when clicking on the register button:
async function onSumitRegisterValues(values: any) {
const options = {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(values),
};
await fetch("http://localhost:3000/api/auth/signup", options)
.then((res) => res.json())
.then((data) => {
if (data?.ok) router.push("http://localhost:3000");
});
}
The values form contains nickname, email, password and cpassword to confirm password.
im getting a 500 on post
Server Error
TypeError: resolver is not a function
This error happened while generating the page. Any console logs will be displayed in the terminal window.
Maybe its my lack of knowledge with trpc and next but ngl, its making me want to separate my backend into something different. But since im not rushing in building this project i really want to try to figure out what i shoud be doing better.
Why are you using fetch instead of using your useQuery method from trpc? The whole point of trpc is that you can skip fetch and will also have type safety.
https://trpc.io/docs/useQuery

ReduxToolkit how to pass custom error from API into CreateAsync thunk and CreateReducer

I want to display custom error from API request but I completely don't know how to do this via redux toolkit.
Below you can see the example.
API:
auth = async (payload) => {
return await this.api.post(payload)
}
action:
export const auth = createAsyncThunk('api/auth', async (payload) => {
const response = await api.auth(payload)
if (response.status != 200) {
return response.data
}
})
reducer:
export default createReducer(initialState, builder => builder.addCase(auth.rejected, (state, action) => {
state.error = action.error.message // here I want to set API error response
}))
The problem is that I don't know how to pass error message from API to reducer action.error.message - is serializedError as default

Sync user with Firebase functions to Hasura GraphQL

I want to use firebase to authenticate users and then firebase functions to insert users into Hasura but having problems with the firebase functions.
When I try to create a user from the app the "registerUser" function, which can be found below, it ends with an error:
Error detected in registerUser:
{"#type":"type.googleapis.com/google.devtools.clouderrorreporting.v1beta1.Insight",
"errorGroup":"CLic1cmw6emOsAE",
"errorEvent":{"message":"Error: The uid must be a non-empty string with at most 128 characters.
at FirebaseAuthError.FirebaseError [as constructor] (/srv/node_modules/firebase-admin/lib/utils/error.js:42:28)
at FirebaseAuthError.PrefixedFirebaseError [as constructor] (/srv/node_modules/firebase-admin/lib/utils/error.js:88:28)\
at new FirebaseAuthError (/srv/node_modules/firebase-admin/lib/utils/error.js:147:16)
at AuthRequestHandler.AbstractAuthRequestHandler.setCustomUserClaims (/srv/node_modules/firebase-admin/lib/auth/auth-api-request.js:996:35)
at Auth.BaseAuth.setCustomUserClaims (/srv/node_modules/firebase-admin/lib/auth/auth.js:342:40)
at exports.registerUser.functions.https.onCall (/srv/index.js:32:18)
at func (/srv/node_modules/firebase-functions/lib/providers/https.js:272:32)
at corsHandler (/srv/node_modules/firebase-functions/lib/providers/https.js:292:44)\n at cors (/srv/node_modules/cors/lib/index.js:188:7)
at /srv/node_modules/cors/lib/index.js:224:17","eventTime":"2020-06-10T08:25:03.017Z","serviceContext":{"service":"registerUser","resourceType":"cloud_function"}}}
If I instead create a user directly via the firebase console my "processSignUp" runs
but ends with another error:
ReferenceError: fetch is not defined
at GraphQLClient.<anonymous> (/srv/node_modules/graphql-request/dist/src/index.js:108:25)
at step (/srv/node_modules/graphql-request/dist/src/index.js:44:23)
at Object.next (/srv/node_modules/graphql-request/dist/src/index.js:25:53)
at /srv/node_modules/graphql-request/dist/src/index.js:19:71
at new Promise (<anonymous>)
at __awaiter (/srv/node_modules/graphql-request/dist/src/index.js:15:12)
at GraphQLClient.request (/srv/node_modules/graphql-request/dist/src/index.js:98:16)
at exports.processSignUp.functions.auth.user.onCreate (/srv/index.js:60:25)
at cloudFunction (/srv/node_modules/firebase-functions/lib/cloud-functions.js:132:23)
at /worker/worker.js:825:24
I've tried pretty much everything I could think of. I've used https://hasura.io/jwt-config/ to setup the JWT on Heroku. I've triple checked passwords and graphQL endpoint. I have no problems with the mutations or query variables when I play around in hasura console but I'm unable to connect the firebase functions to hasura. Thanks in advance.
functions/index.js
...
const client = new request.GraphQLClient(
"https://app-name.herokuapp.com/v1/graphql",
{
headers: {
"content-type": "application/json",
"x-hasura-admin-secret": "Password",
},
}
);
...
// On register.
exports.registerUser = functions.https.onCall((data) => {
const { email, password } = data;
try {
const userRecord = admin.auth().createUser({ email, password });
const customClaims = {
"https://hasura.io/jwt/claims": {
"x-hasura-default-role": "user",
"x-hasura-allowed-roles": ["user"],
"x-hasura-user-id": userRecord.uid,
},
};
admin.auth().setCustomUserClaims(userRecord.uid, customClaims);
return userRecord.toJSON();
} catch (e) {
let errorCode = "unknown";
let msg = "Something went wrong, please try again later";
if (e.code === "auth/email-already-exists") {
errorCode = "already-exists";
msg = e.message;
}
throw new functions.https.HttpsError(errorCode, msg, JSON.stringify(e));
}
});
...
// On sign up.
exports.processSignUp = functions.auth.user().onCreate(async (user) => {
const { uid: id, email } = user;
const mutation = `
mutation($id: String!, $email: String) {
insert_users(objects: [{
id: $id,
email: $email,
}]) {
affected_rows
}
}
`;
try {
const data = await client.request(mutation, { id, email });
return data;
} catch (e) {
throw new functions.https.HttpsError("invalid-argument", e.message);
}
});
In the package.json for your functions, try changing the node engine to 10 and your grapql-request package to 1.8.2.

Redux Async actions returns me an error: Actions must be plain objects. Use custom middleware for async actions

I am struggling with the async Redux (thunk). I trully don't understand what I am doing wrong with my async actions and why I get the error : Error: Actions must be plain objects. Use custom middleware for async actions.
export async function startLocalizationFetchingAsync(currentLocalizationState) {
return (dispatch) => {
let payload = {
request: {
sent:true,
}
};
dispatch({
type: "NEW_LOCALIZATION_REQUEST_SENT2",
payload: payload,
});
return axios.get("http://freegeoip.net/json/"+currentLocalizationState.clientIP)
.then(res => {
res = res.data;
var payload = {
country: res.country_name||'',
};
dispatch({
type: "NEW_LOCALIZATION",
payload: payload,
});
})
.catch(function (error) {
console.log("Promise Rejected",error);
dispatch({
type: "NEW_LOCALIZATION_REQUEST_ERROR",
payload: null,
});
});
};
}
while in the index.js router i have the following code
async action({ next, store }) {
// Execute each child route until one of them return the result
const route = await next();
await store.dispatch(startLocalizationFetchingAsync());
this generates me an error:
Error: Actions must be plain objects. Use custom middleware for async actions.
dispatch
webpack:///~/redux/es/createStore.js:153
http://myskyhub.ddns.net:3000/assets/client.js:9796:16
http://myskyhub.ddns.net:3000/assets/vendor.js:46309:16
Object.dispatch
webpack:///~/redux-thunk/lib/index.js:14
Object._callee$
webpack:///src/routes/index.js?a731:35
tryCatch
webpack:///~/regenerator-runtime/runtime.js:65
Generator.invoke
webpack:///~/regenerator-runtime/runtime.js:303
Generator.prototype.(anonymous
webpack:///~/regenerator-runtime/runtime.js:117
http://myskyhub.ddns.net:3000/assets/3.9645f2aeaa83c71f5539.hot-update.js:8:361
while the config store is the following
const middleware = [thunk.withExtraArgument(helpers), thunk.withExtraArgument(AsyncMiddleware)];
let enhancer;
if (__DEV__) {
middleware.push(createLogger());
//middleware.push(AsyncMiddleware());
enhancer = compose(
applyMiddleware(...middleware),
devToolsExtension,
);
} else {
enhancer = applyMiddleware(...middleware);
}
initialState.localization = defaultLocalization; //Location
// See https://github.com/rackt/redux/releases/tag/v3.1.0
const store = createStore(rootReducer, initialState, enhancer);
What I am doing wrong? I don't understand the redux-thunk...

Resources