i'm currently using NodeJS.
I'm trying to import a module to a component function and everything executes pretty well, but i still get this error in the server console:
error - src\modules\accountFunctions.js (15:35) # Object.User.GetData
TypeError: _cookieCutter.default.get is not a function
cookieCutter.get is actually a function and is working as inteneded
import cookieCutter from 'cookie-cutter'
import { useSelector, useDispatch } from 'react-redux'
import { useRouter } from 'next/router'
import { accountActions } from '../store/account'
const Auth = require('./auth.module')
const User = {}
User.GetData = async () => {
const route = useRouter()
const userData = useSelector((state) => state.user)
const dispatch = useDispatch()
const sessionId = cookieCutter.get('session')
if (sessionId && userData.username === '') {
const userExist = await Auth.loadUserInformation()
if (userExist.result === false) {
route.push('/login')
return false
}
dispatch(accountActions.updateAccountInformation(userExist.data))
return true
} else if (!sessionId) {
route.push('/login')
return false
}
}
module.exports = User
I know for a fact that a solution would be importing the library into the function compoenent but i really don't wanna keep on importing it everywhere.
This is how i'm importing the module.
import User from '../src/modules/accountFunctions'
const dashboard = () => {
console.log('Rance')
User.GetData()
return <NavBar />
}
export default dashboard
You need to move the cookie fetching logic to a useEffect inside the custom hook, so it only runs on the client-side. Calling cookieCutter.get won't work when Next.js pre-renders the page on the server.
const useUserData = async () => {
const route = useRouter()
const userData = useSelector((state) => state.user)
const dispatch = useDispatch()
useEffect(() => {
const getAuthenticatedUser = async () => {
const sessionId = cookieCutter.get('session')
if (sessionId && userData.username === '') {
const userExist = await Auth.loadUserInformation()
if (userExist.result === false) {
route.push('/login')
}
dispatch(accountActions.updateAccountInformation(userExist.data))
} else if (!sessionId) {
route.push('/login')
}
}
getAuthenticatedUser()
}, [])
}
Related
react native passing const and expect string erorr
I'm trying to pass apple key but im getting an error saying that const apikey : google string ... any idea ?
import { useEffect, useState } from "react";
import { Platform } from "react-native";
import Purchases,{
CustomerInfo,
PurchasesOffering,
} from "react-native-purchases";
const APIKeys = {
apple: "appl_KDUGooX",
google: "your_revenuecat_api_key",
};
const typeOfMembership = {
monthly: "proMonthly",
yearly: "proYearly",
};
function useRevenueCat(){
const [currentOffering,setCurrentOffering] =
useState<PurchasesOffering | null>(null);
const [customerInfo,setCustomerInfo] =
useState<CustomerInfo | null>(null);
const isProMember =
customerInfo?.activeSubscriptions.includes(typeOfMembership.monthly) ||
customerInfo?.activeSubscriptions.includes(typeOfMembership.yearly);
useEffect(() => {
const fetchData = async () => {
Purchases.setDebugLogsEnabled(true);
if (Platform.OS == "android") {
await Purchases.configure({ apikey: APIKeys.google });
} else {
await Purchases.configure({ apikey: APIKeys.apple });
}
const offering = await Purchases.getOfferings();
const customerInfo = await Purchases.getCustomerInfo();
}
},[])
}
export default useRevenueCat;
Where can i change it to make it correctly ??
I am trying to set an array of objects into dineIns after fetching them inside useEffect. What I understood is that there is some kind of delay in receiving the data because the state variable returns an empty array when I log it after fetching the data.
import axios from 'axios';
import React, { useEffect, useState } from 'react';
import { useNavigate } from 'react-router';
import jwtDecode from 'jwt-decode';
function CheckIns() {
const [dineIns, setDineIns] = useState([]);
const navigate = useNavigate();
useEffect(() => {
const token = localStorage.getItem('token');
if (token) {
const user = jwtDecode(token);
if (!user) {
localStorage.removeItem('token');
navigate('/login');
} else {
async function UserData(user_email) {
const user_data = await axios
.get(`/api/users/${user_email}`)
.then((res) => {
const info = res.data.reservations;
setDineIns(info);
console.log(dineIns);
});
}
UserData(user.email);
}
} else {
navigate('/login');
}
}, []);
}
What needs to be corrected here to set the state in time?
set state is an async operation, which log the data after set it, will log the old value.
To ensure that the data set correctly, you can use setState again
const info = res.data.reservations
setDineIns(info)
setDineIns(prev => {
console.log(prev)
return prev;
})
Or you can use effect with dineIns dependence.
I think your code works fine.
You are expecting a Promise from the axios call but you are awaiting it.
Try to change your code like this:
useEffect(() => {
const token = localStorage.getItem('token');
if (token) {
const user = jwtDecode(token);
if (!user) {
localStorage.removeItem('token');
navigate('/login');
} else {
async function UserData(user_email) {
try {
const { data } = await axios.get(`/api/users/${user_email}`);
setDineIns(data.reservations);
console.log(dineIns);
} catch (err) {
console.log(err);
}
}
UserData(user.email);
}
} else {
navigate('/login');
}
}, []);
Hello I have custom hook
code is like below
import * as React from 'react'
export const myCustomHook = (props?: boolean) => {
const [value, setValue] = React.useState([]);
React.useEffect(() => {
return (async (p1) => {
// ....
setValue(someValues)
})
}, [])
const myFun = async (prop1) => {
// ... some operations
return {id: id}
}
return { myFun, value }
}
I am using the above like this
const { value, myFun } = myCustomHook();
const foofun = async (pp) => {
const myfunRes = await myFun(prop1);
}
Now I want to put myFun in useEffect
Please help me with this.
I am trying to create an editor to update my backend data but I am stuck at sending data from client to backend
Here is my following front-end code:
import React, { useState } from "react";
import dynamic from "next/dynamic";
import { convertToRaw, EditorState, getDefaultKeyBinding } from "draft-js";
import draftToHtml from "draftjs-to-html";
const Editor = dynamic(
() => import("react-draft-wysiwyg").then((mod) => mod.Editor),
{ ssr: false }
);
const Missions = ({ teamData, editable }) => {
const { title, mission, teamId } = teamData;
const classes = useStyle();
const [missionContent, setMissionContent] = useState(mission);
const [editing, setEditing] = useState(false);
const [editorState, updateEditorState] = useState(EditorState.createEmpty());
const onEditorStateChange = (editData) => {
updateEditorState(editData);
};
const handleSave = async () => {
const selection = editorState.getSelection();
const key = selection.getAnchorKey();
const content = editorState.getCurrentContent();
const block = content.getBlockForKey(key);
const type = block.getType();
if (type !== "unordered-list-item" && type !== "ordered-list-item") {
if (
editorState.getCurrentContent().getPlainText("").trim().length !== 0
) {
const content = editorState?.getCurrentContent();
let html = await draftToHtml(convertToRaw(content));
await updateEditorState(EditorState.createEmpty(""));
setMissionContent(html.trim());
}
}
setEditing(false);
};
return (
<div className="team-mission-editor-container">
<Editor
wrapperClassName={"mission-editor-wapper"}
toolbarClassName={"mission-editor-toolbar"}
editorClassName={"mission-editor-editor"}
editorState={editorState}
onEditorStateChange={onEditorStateChange}
toolbar={{...}}
/>
)
Here is my back-end router:
router.put(
"/team/:teamId",
restrictedRoute,
checkData,
catchErrors(checkTeamPermissions),
catchErrors(updateTeamData)
);
and here is my update function from backend:
exports.updateTeamData = async (req, res) => {
// Get userId
const userId = req.session.passport.user.id;
// Get teamId
const publicTeamId = req.params.teamId;
// Fetch private id for team
const teamId = await getTeamId(publicTeamId);
// The user making the request
const userPublicId = req.session.passport.user.publicId;
// The creator of the team
const creatorPublicId = req.body.creator;
// Check who is making the request
if (userPublicId !== creatorPublicId) {
res.status(401).json("msg: You cant update a team you did not create");
}
// Updates
const payload = {
title: req.body.title,
mission: req.body.mission,
inputs: req.body.inputs,
outputs: req.body.outputs,
duration_in_months: req.body.duration_in_months,
status: req.body.status,
mergedTo: teamId,
};
// Update team data
await models.Team.update(payload, {
where: {
id: teamId,
creatorId: userId,
},
});
res.status(200).json("msg: Updated team successfully");
};
How can I send data fromo my editor to backend and update it?
Thank you so much for helping me
I am using NextJS with next-i18next. This is my home page:
import {withTranslation} from '../config/next-i18next';
const Home = function Home() {
return (<div>test</div>)
};
Home.getInitialProps = async () => {
return {namespacesRequired: ['home']}
};
export default withTranslation('home')(Home);
What I want is to get current language inside a component/page, how can I do that ?
withTranslation injects the i18n object.
import {withTranslation} from '../config/next-i18next';
const Home = function Home({ i18n }) {
return (<div>{i18n.language}</div>)
// ----------------^
};
Home.getInitialProps = async () => {
return {namespacesRequired: ['home']}
};
export default withTranslation('home')(Home);
Or using Hooks,
import {useTranslation} from '../config/next-i18next';
const Home = function Home() {
const { i18n } = useTranslation('home');
return (<div>{i18n.language}</div>)
// ----------------^
};
Home.getInitialProps = async () => {
return {namespacesRequired: ['home']}
};
export default Home;
With Next.js you could also use the useRouter hook.
import {withTranslation} from '../config/next-i18next';
import { useRouter } from 'next/router'
const Home = function Home() {
const router = useRouter()
const currentLang = router.locale // => locale string eg. "en"
return (<div>test</div>)
};
Home.getInitialProps = async () => {
return {namespacesRequired: ['home']}
};
export default withTranslation('home')(Home);