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 ??
Related
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'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()
}, [])
}
I have been trying to implement a LIKE system for my social media application with react at client-side and express at server-side. I'm trying to fetch the current LIKE stats using "axios" within a "useEffect". But, the data returned after "GET" request is an empty array instead of actual data. The data is being saved to mongoDB and it could be fetched using "POSTMAN", but cannot be fetched from the client-side. Any fixes?
Like.jsx
// Client-side where LIKE stats are fetched
import axios from 'axios';
import { useContext, useEffect, useState } from 'react';
import { useLocation } from 'react-router';
import { Context } from '../../context/Context';
import './reactions.css'
export default function Reactions() {
const LIKE = "LIKE"
const { user } = useContext(Context)
const location = useLocation()
const postId = location.pathname.split("/")[2]
const [likes, setLikes] = useState(0)
const [refresh, setRefresh] = useState(false)
useEffect(() => {
const fetchReactions = async () => {
const likeRes = await axios.get(`/reactions/all`, {
data: {
postId,
reactionType: LIKE
}
})
console.log("Like res data", likeRes.data) // The logged array is empty :(
setLikes(likeRes.data.length)
}
fetchReactions()
}, [postId, refresh])
const handleReact = async (reactionType) => {
const newReaction = {
reactionType,
username: user.username,
postId,
}
try {
const res = await axios.post("/reactions", newReaction)
console.log(res.data) // The logged object has data :)
setRefresh(!refresh)
} catch(err) {
console.log(err)
}
}
Like.js
// Reaction model at server-side
const mongoose = require("mongoose")
const ReactionSchema = new mongoose.Schema(
{
reactionType: {
type: String,
required: true,
},
username: {
type: String,
required: true,
},
postId: {
type: String,
required: true,
}
},
{
timestamps: true,
}
)
module.exports = mongoose.model("Reaction", ReactionSchema)
likes.js
// API for creating and fetching LIKES
const router = require("express").Router()
const Reaction = require("../models/Reaction")
// CREATE REACTION
router.post("/", async (req, res) => {
const newReaction = new Reaction(req.body)
try {
const savedReaction = await newReaction.save()
res.status(200).json(savedReaction)
} catch(err) {
res.status(500).json(err)
}
})
// GET REACTIONS OF A POST
router.get("/all", async (req, res) => {
try {
const reactions = await Reaction.find({
postId: req.body.postId,
reactionType: req.body.reactionType,
})
res.status(200).json(reactions)
} catch(err) {
res.status(500).json(err)
}
})
module.exports = router
Thanks to #cmgchess for making me think about my approach of making a "GET" request with request body.
I changed the body parameters to query parameters and it did WORK :)
changed Like.jsx
// Client-side where LIKE stats are fetched
import axios from 'axios';
import { useContext, useEffect, useState } from 'react';
import { useLocation } from 'react-router';
import { Context } from '../../context/Context';
import './reactions.css'
export default function Reactions() {
const LIKE = "LIKE"
const { user } = useContext(Context)
const location = useLocation()
const postId = location.pathname.split("/")[2]
const [likes, setLikes] = useState(0)
const [refresh, setRefresh] = useState(false)
useEffect(() => {
const fetchReactions = async () => {
// ---- DIFF OPEN ----
const search = `?postId=${postId}&reactionType=${LIKE}`
const likeRes = await axios.get(`/reactions${search}`)
// ---- DIFF CLOSE ----
console.log("Like res data", likeRes.data) // The logged array has data :)
setLikes(likeRes.data.length)
}
fetchReactions()
}, [postId, refresh])
const handleReact = async (reactionType) => {
const newReaction = {
reactionType,
username: user.username,
postId,
}
try {
const res = await axios.post("/reactions", newReaction)
console.log(res.data) // The logged object has data :)
setRefresh(!refresh)
} catch(err) {
console.log(err)
}
}
changed likes.js
// API for creating and fetching LIKES
const router = require("express").Router()
const Reaction = require("../models/Reaction")
// CREATE REACTION
router.post("/", async (req, res) => {
const newReaction = new Reaction(req.body)
try {
const savedReaction = await newReaction.save()
res.status(200).json(savedReaction)
} catch(err) {
res.status(500).json(err)
}
})
// GET REACTIONS OF A POST
// --- DIFF OPEN ---
router.get("/", async (req, res) => {
const postId = req.query.postId
const reactionType = req.query.reactionType
try {
const reactions = await Reaction.find({
postId,
reactionType
})
// --- DIFF CLOSE ---
res.status(200).json(reactions)
} catch(err) {
res.status(500).json(err)
}
})
module.exports = router
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);