How to send data from react editor to server? - node.js

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

Related

telegram api signup return PHONE_CODE_INVALID

my code:
const { Api, TelegramClient } = require("telegram");
const { StringSession } = require("telegram/sessions");
const { Logger } = require("telegram/extensions");
const apiId = 22;
const apiHash = "333333";
const phoneNumber = "9996627328";
const phoneCode = "22222";
const createClient = async (stringSession) => {
const session = new StringSession(stringSession);
const options = { connectionRetries: 5, baseLogger: new Logger("debug") };
const client = new TelegramClient(session, apiId, apiHash, options);
client.session.setDC(2, "149.154.167.40", 443);
await client.connect();
return client;
};
const getLoginCodeCommand = (phoneNumber) => {
const settings = new Api.CodeSettings();
const args = { phoneNumber, apiId, apiHash, settings };
return new Api.auth.SendCode(args);
};
(async () => {
const client = await createClient("");
const response = await client.invoke(getLoginCodeCommand(phoneNumber));
console.log('responseļ¼š', response);
const { phoneCodeHash } = response;
const result22 = await client.invoke(
new Api.auth.SignUp({
phoneNumber: phoneNumber,
phoneCodeHash: phoneCodeHash,
firstName: "liu",
lastName: "some",
})
);
console.log("RESULT22", result22);
})();
response:
/Users/xizao/work/fm/project/telegram/node_modules/telegram/errors/index.js:28
return new RPCBaseErrors_1.RPCError(rpcError.errorMessage, request, rpcError.errorCode);
^
RPCError: 400: PHONE_CODE_INVALID (caused by auth.SignUp)
at RPCMessageToError (/Users/xizao/work/fm/project/telegram/node_modules/telegram/errors/index.js:28:12)
at MTProtoSender._handleRPCResult (/Users/xizao/work/fm/project/telegram/node_modules/telegram/network/MTProtoSender.js:517:58)
at MTProtoSender._processMessage (/Users/xizao/work/fm/project/telegram/node_modules/telegram/network/MTProtoSender.js:442:15)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async MTProtoSender._recvLoop (/Users/xizao/work/fm/project/telegram/node_modules/telegram/network/MTProtoSender.js:418:17) {
code: 400,
errorMessage: 'PHONE_CODE_INVALID'
}
No matter how you adjust it, the phone code is always invalid
The correct result should be direct registration success.
I haven't been able to find the problem because of what? Please help me to see why?
doc link: https://gram.js.org/tl/auth/SignUp#authsignup

Wrong between const and string

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 ??

Create private chat with MERN and Socketio

i want to send message to specific user from react-autocomplete dropdown menu with select and display that message in their own window. And also i am trying to save messages to my mongodb but when i check mongocompass server it is only showing me the _id and and when i click send button in front end it is sending same message multiple times .Here is what i have so far but it is sending the message to everyone. i need help to get my code right to create private chat with saving correctly to db and retrieve messages everytime page refreshes
CLIENT:
const [username, setUsername] = useState("");
const [onlineUsers, setOnlineUsers] = useState([]);
const [chatHistory, setChatHistory] = useState([]);
const ADDRESS = "http://localhost:1337";
const socket = io(ADDRESS, { transports: ["websocket"] });
useEffect(() => {
socket.on("connect", () => {
console.log("Connection established!");
});
socket.on("loggedIn", () => {
console.log("Successfully logged in");
fetchOnlineUsers();
});
socket.on("newConnection", () => {
console.log("Look! another client connected!");
fetchOnlineUsers();
});
socket.on("message", (newMessage) => {
console.log("new message received!", newMessage);
setChatHistory((currentChatHistory) => [
...currentChatHistory,
newMessage,
]);
});
}, []);
const handleSubmitMessage =(e)=> {
e.preventDefault();
const messageToSend = {
text: message,
sender: username,
id: socket.id,
timeStamp: Date.now()
}
socket.emit("sendmessage", messageToSend)
setChatHistory([...chatHistory, messageToSend])
setMessage("")
}
const handleOnSearch = (string, results) => {}
const handleOnHover = (result) => {}
const handleOnSelect = (item) => {
console.log("ITEM",item);
}
const handleOnFocus = () => {}
const formatResult = (item) => {
return (
<>
<span style={{ display: 'block', textAlign: 'left' }}>{item.username}</span>
</>
)
}
SERVER CODE
import express from "express";
import cors from "cors";
import mongoose from "mongoose";
import listEndpoints from "express-list-endpoints";
import { Server } from "socket.io";
import { createServer } from "http";
import MsgModel from './db/schema.js'
const { MONGO_URL } = process.env;
const app = express();
app.use(cors());
app.use(express.json());
const server = createServer(app);
const io = new Server(server);
const port = process.env.PORT || 1337;
let onlineUsers = [];
io.on("connect", (socket) => {
socket.join("main-room")
socket.on("setUsername", ({ username }) => {
onlineUsers = onlineUsers
.filter((user) => user.username !== username)
.concat({
username: username,
id: socket.id,
});
socket.emit("loggedIn");
socket.broadcast.emit("newConnection");
});
socket.on("sendmessage", (msg) => {
console.log("sendmessage",msg);
const saveMessageToDb = new MsgModel({msg:msg})
saveMessageToDb.save().then(()=> {
socket.to("main-room").emit("message", msg)
})
})
app.get("/online-users", (req, res) => {
res.send({ onlineUsers });
});
MONGOOSE SCHEMA
import mongoose from "mongoose";
const { Schema, model } = mongoose;
const msgSchema = new Schema(
{
msg: { type: String },
},
{ typeKey: '$type' }
);
export default model("Message", msgSchema);

Why is the response (payment Intent) after completing the payment undefined?

myReactApp/functions/index.js
const functions = require("firebase-functions");
const express = require("express");
const cors = require("cors");
const stripe = require('stripe')
('sk_test_**********');
// API
// App config
const app = express();
// Middlewares
app.use( cors({origin:true}) );
app.use(express.json());
// API routes
app.get('/', (request, respond) => respond.status(200).send("page is working") );
app.post('/payment/create', async (request, response) => {
const total = request.query.total;//get the value of total from URL using query
console.log('payment request recived >>>' , total);
const paymentIntent = await stripe.paymentIntents.create({
amount: total,
currency: 'USD'
})
response.status(201).send({
clientSecret : paymentIntent.client_secret,
})
})
//http://localhost:5001/clone-21937/us-central1/api
// Listen command
exports.api = functions.https.onRequest(app);
myReactApp/src/payment.js
import React, { useEffect, useState } from 'react';
import Orders from './Orders';
import CheckoutProduct from './CheckoutProduct';
import CurrencyFormat from 'react-currency-format';
import { CardElement, useElements, useStripe } from '#stripe/react-stripe-js';
import { collection, addDoc, setDoc } from 'firebase/firestore/lite'
import { Link, useNavigate } from 'react-router-dom';
import { useStateValue } from './StateProvider';
import { db } from './firebase';
import axios from './axios';
const Payment = () => {
const stripe = useStripe();
const elements = useElements();
const navigate = useNavigate();
const [{ basket, subtotal, user }, dispatch] = useStateValue();
const [succeeded, setSucceeded] = useState(false);
const [processing, setProcessing] = useState('');
const [error, setError] = useState(null);
const [disabled, setDisabled] = useState(true);
const [clientSecret, setClientSecret] = useState(true);
useEffect(() => {
const getClientSecret = async () => {
const response = await axios({
method: 'POST',
url: `/payment/create?total=${subtotal * 100}`
});
//clientSecret is the amount to be paid
//fetching the clientSecret send from response (Index.js)
setClientSecret(response.data.clientSecret);
}
getClientSecret();
}, [basket]);
//handle submitting the form
const handleSubmit = async (event) => {
event.preventDefault();
setProcessing(true);
const payload = await stripe.confirmCardPayment(clientSecret, {
payment_method: {
card: elements.getElement(CardElement)
}
}).then( ({paymentIntent}) => {
console.log(paymentIntent);//undefined
try {
addDoc(
collection(db,'users', user?.uid, 'orders'),{
basket:basket
}
)
}
catch (error) {
alert(error.message);
}
//empty the basket after order
dispatch({
type: 'EMPTY_BASKET'
})
setSucceeded(true);
setProcessing(false);
setError(null);
// navigate('/orders');
})
}
const handleChange = (event) => {
setDisabled(event.empty);
setError(event.error ? event.error.message : '');
}
return (
<div className="payment_sectionTransaction">
<form onSubmit={handleSubmit}>
<CardElement className='payment_cardElement' onChange={handleChange}/>
<CurrencyFormat
value={subtotal}
prefix={'$'}
decimalScale={2}
thousandSeparator={true}
displayType={'text'}
renderText={(value) => {
return <>
<p><strong>Amount: {value}</strong></p>
</>
}} />
<button type='submit' disabled={processing || succeeded || disabled} >
{processing ? 'Processing..' : 'Confirm Order'}
</button>
</form>
</div>
)
}
export default Payment
After payment I am trying to get the response-paymentIntent but it shows to be undefined.
I can see the payment in the stripe dashboard so may be payment sections is all good but response after the payment is not good.
I also get this error in console after payment get done:
POST http://localhost:5001/clone-21937/us-central1/api/payment/create?total=0 net::ERR_FAILED 200
getClientSecret is async function. You must write code look like
const result = await getClientSecret();

axios.get() isn't fetching the data at client side

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

Resources