Parsing the text with React from server with Draft.js - javascript

I'm trying out Draft.js with my React application running with a GraphQL server. Currently I have a editor where I can type and add code blocks and submit it to the server. Here's the code for that:
const contentState = this.state.editorState.getCurrentContent()
const { content } = this.state.values
console.log('raw', convertToRaw(contentState))
let response;
try {
response = await this.props.mutate({
variables: {
content: JSON.stringify(contentState)
},
})
console.log(response)
response gives me
And that's no good. I rather have the convertToRaw(contentState) since that gives me:
The reason why I'm not doing convertToRaw(contentState) at mutate is because it gives me this error:
contentState.getBlockMap is not a function
So my questions are how can I use the convertToRaw function when submitting the text to the server and how can I later parse the text on the frontend so it wont look like this:
Thanks for reading my question. All help is appreciated!
Have a great day.

Related

JSON error in javascript when using websockets

I seem to be overlooking an error in my code that I just can't figure out. I have read multiple online sources showing what the error can be, but I can't find it in my code.
I am using WebSockets to communicate between my front and backend, when sending data in JSON format from my front to backend, it works perfectly, but not the other way around.
In my code snippets, I replaced my data with dummy values to make it easier to see the error.
Backend:
some_code.js
var msg = {"a": "a"};
Websocket.Send(msg);
websocket.js
Websocket.Send = (msg) =>
{
Websocket.Socket.clients.forEach(function each(client)
{
client.send(JSON.stringify(msg));
});
}
Frontend:
websocket.js
Socket.addEventListener("message", ({msg}) =>
{
console.log(JSON.parse(msg));
});
Error:
Any help will be appreciated, thanks!
Ok so changing the code of websocket.js to the following fixed it.
websocket.js
Socket.addEventListener("message", ({data}) =>
{
console.log(JSON.parse(data));
});
So it seems that the WebSocket library requires the variable name holding the received data to be named "data".

Problem using google spreadsheet as source for a Next.JS website: changes won't update pages

I made this restaurant's website and uses Google Spreadsheet to feed content into the menu pages. The choice of such method was based on simplicity and client expertise.
I'm using google-spreadsheet package to fetch all the information I need from this document on Google Drive...
//** ../pages/api/cardapios/index.js
import { GoogleSpreadsheet } from "google-spreadsheet";
export default async function getCardapioFromSlug(indexNumber) {
try {
const doc = new GoogleSpreadsheet(<%GOOGLE_SPREADSHEET_ID%>)
await doc.useServiceAccountAuth({
client_email: process.env.GOOGLE_SHEETS_SERVICE_ACCOUNT_EMAIL,
private_key: process.env.GOOGLE_SHEETS_PRIVATE_KEY,
});
await doc.loadInfo()
const cardapio = doc.sheetsByIndex[indexNumber]
const rows = await cardapio.getRows()
if (rows.length) {
return rows.map(({
Código,
Produto,
Unidade,
Descrição,
Valor,
Procedência,
Categoria
}) => {
return {
Código,
Produto,
Unidade,
Descrição,
Valor,
Procedência,
Categoria
}
})
}
} catch (err) {
console.log(err)
}
return [];
}
...then feeding it into the page using getStaticProps() function. It worked like a charm once I've got all things setup properly.
// ../pages/unidades/[slug].js
export async function getStaticProps({ params }) {
const sanityData = await getCardapio(params.slug)
const indexNumber = sanityData[0].id
// console.log("index number", indexNumber)
const produtos = await getCardapioFromSlug(indexNumber)
const produtosStringfied = JSON.stringify(produtos)
const produtosArray = JSON.parse(produtosStringfied)
return {
props: {
cardapio: {
info: sanityData[0] || null,
items: produtosArray || null
}
},
revalidate: 1
}
}
The problem is after we changed values for some cells in the source document, the content wasn't automatically updated in the site.
I've tried redeploying (with both build cache on and off) it so the build process would grab the content from the document one more time and update the site, but it didn't worked. One idea was to make a webhook that would be avaiable for the client to run a simple command on his machine and rebuild the page with the new info, but this approach seems to be useless.
I red some articles (this one for instance) on custom webhooks for Google Spreadsheets but I can't really understand how it would trigger something on my page. Don't really think it would actually work.
Now I'm kind of stuck on where should I go. Perhaps I should rewrite my getStaticProps()?
The issue has nothing to due with the code itself, but the misuse of the API. The id from the spreadsheet was wrong, still using a prototype which was used as base to the final one the client has. Changed the env var and everything went fine.
Had to force deploy ignoring build cache via vercel cli. Thanks to anyone that spent time commenting and wondering about this issue.

How can you integrate a variable in a JSON path in JavaScript

First of all, it's connecting to a url and just sanitizing it all in the Front-End. The Hypixel API works so, that you take the api url for the wanted request, in this case api.hypixel.net/player?name=USERNAME&key=APIKEY, and get back a big JSON file, which my code should sanitize. So, if you're using the Hypixel API, yeah you're sending the API-Key through the browser, but that is a security flaw in the Hypixle API and not in my code. The sole purpose of my code is to learn more about JavaScript an show it to others.
I'm working on an API access to the Hypixel API.
This gets me a JSON, in which I want to get a specific game, that was inputted in a field an is saved in a dict.
I'm trying to integrate this like this (console.log is only for test purposes, until I give back the data to HTML):
let values = Array.from(document.querySelectorAll('#apiForm input'))
.reduce((acc, input) => {
return { ...acc, [input.id]: input.value };
}, {})
fetch(`https://api.hypixel.net/player?name=${values.name}&key=${values.key}`)
.then(result => result.json())
.then(result => {
if (result.success) {
if (values.game in result.player.stats) {
console.log(result.player.stats.$(values.game)) //not working
} else {
console.log(result.player.stats)
console.log('Game not available or not played yet')
}
} else {
console.log('Something went wrong, please check your name and API-Key or try again later')
}
})
How can I do this here?
The API-Form looks like this:
And the JSON file looks like this:
So when I input Bedwars for example, the path I want should result in result.player.stats.Bedwars:
Replace result.player.stats.$(values.game) with
result.player.stats[values.game]
Also, when putting user input into URI paths, sanitize it with encodeURIComponent or build the query string with new URLSearchParams({ ...props }).toString().

Using json online

Heyo!
So, I'm trying to make something like https://aws.random.cat/meow however, when using my code with a discord bot, it isn't working.. It makes me wonder if you can host json things online directly by using the below code:
document.body.innerHTML = "<pre style=\"word-wrap: break-word; white-space: pre-wrap;\">{\"file\":\"https:\\/\\/"+domain+"\\/images\\/hug\\/"+item+"\"}</pre>";
Furthermore, my bot code is:
const { MessageEmbed } = require('discord.js');
const axios = require('axios');
const {get} = require("snekfetch");
const embed = new MessageEmbed()
.setColor("RANDOM")
.setTitle("thingie")
.setDescription("Loading...")
message.channel.send(embed).then(msg => {
get('https://example.com/kiss').then(response => {
setTimeout(function(){
embed.setDescription("")
embed.setImage(response.body.file)
msg.edit(embed)
}, 1500);
});
})
My website is working perfectly and is showing exactly as in https://aws.random.cat/meow However, it still doesn't work. Please lmk how or why this is happening.
P.S I didn't include the modules.export part in the bot code cuz, I thought it was extra.
P.P.S The following is my current output: This
Thanks!
If you want to provide data in a JSON format on your endpoint then just provide the JSON part, no need to put it in an HTML. If you put your JSON inside HTML like a string, then when you do get(<your url>) you'll get the entire HTML code with the embedded JSON, and so response.file doesn't work.
The reason why https://aws.random.cat/meow shows up as being embedded within HTML is because the browser detects that it is a JSON file and hence it does the embedding automatically. Here is the RAW response from that URL when you try to make the request using wget on the command line:
$ wget https://aws.random.cat/meow --no-check-certificate
$ cat meow
{"file":"https:\/\/purr.objects-us-east-1.dream.io\/i\/935392_10151612620866211_62628372_n.jpg"}
As you can see, there's no HTML around it. It's pure JSON.
To verify that this is indeed the case, log the response you get from your url:
get('https://example.com/kiss').then(response => {
console.log(response.body);
});
Unrelated: anyone else appreciate the cat meow coincidence here?

Express routing to search results

Got a real newbie question here. So i'm building an events page in which I'd like to filter results by date input (standard html form). I've made this a get request with the following routing:
app.get("/eventByDate/:date", async (req, res) => {
const d = req.params.date;
const data = await Event.find({ date: d });
if (data) {
res.render(`./events/eventByDate`, { data });
} else {
console.log("THERE IS NO DATA");
}
});
EventByDate is its own page, and I can access the relevant stuff by manually typing, for example, http://localhost:3000/eventByDate/2021-01-20
But as it is just now, the form submit takes me there but with the query string in the title, i.e. http://localhost:3000/eventByDate/?date=2021-01-20
Does anyone have a solution to this? My initial idea was to try to remove the query string but this seems a little inelegant, so I'm sure there is a simpler way that I'm completely missing?
Thanks in advance.

Categories