What part of the react-quilljs object should I save to the database in the backend?
I am trying to use react-quilljs to implement text editor in a full mern stack app, but I am not sure what part of the quill object should I save to the database in the backend. I have the follow code for the editor:
import React, { useState } from 'react';
import { useQuill } from 'react-quilljs';
// or const { useQuill } = require('react-quilljs');
import 'quill/dist/quill.snow.css'; // Add css for snow theme
// or import 'quill/dist/quill.bubble.css'; // Add css for bubble theme
export default () => {
const { quill, quillRef } = useQuill();
const [content, setContent] = useState('');
console.log(quill); // undefined > Quill Object
console.log(quillRef); // { current: undefined } > { current: Quill Editor Reference }
React.useEffect(() => {
if (quill) {
quill.on('text-change', () => {
setContent(?) // What part of the quill object I need to use here to set the content before sending it to the backend <-----------------
console.log(quill.getFormat());
console.log('Text change!');
});
}
}, [quill]);
const submitHandler = (e) => {//here I will send the editor content to the bakcend};
return (
<div style={{ width: 500, height: 300 }}>
<div ref={quillRef} />
<form onSubmit={submitHandler}>
<button type='submit'>Submit</button>
</form>
</div>
);
};
1 answer
-
answered 2021-04-08 05:49
Goutham J.M
You should save two things separately one is Raw data of the Quill and another is extracting only text from it
Refer to the sandbox below , you need to save the content
https://codesandbox.io/s/react-quill-demo-forked-0qr5f?file=/src/editor.js
See also questions close to this topic
-
How to devise this solution to Non-Constructible Change challenge from Algoexpert.io
I'm working through algoexpert.io coding challenges and I'm having trouble undersatnding the suggested solution to one of the questions titled Non-Constructible Change
Here's the challenge question:
Given an array of positive integers representing the values of coins in your possession, write a function that returns the minimum amount of change (the minimum sum of money) that you cannot create. The given coins can have any positive integer value and aren't necessarily unique (i.e., you can have multiple coins of the same value).
For example, if you're given coins = [1, 2, 5], the minimum amount of change that you can't create is 4. If you're given no coins, the minimum amount of change that you can't create is 1.
// O(nlogn) time, O(n) size. function nonConstructibleChange(coins) { coins = coins.sort((a, b) => a - b); // O(nlogn) time operation let change = 0; for (coin of coins) { if (coin > change + 1) return change + 1; change += coin; } return change + 1; }
My problem
I am not completely sure how did the author of the solution come up with the intuition that
if the current coin is greater than `change + 1`, the smallest impossible change is equal to `change + 1`.
I can see how it tracks, and indeed the algorithm passes all tests, but I'd like to know more about a process I could use to devise this rule.
Thank you for taking the time to read the question!
-
My document is not defined because of lost context
Working with vanilla.js and my code looks like this:
class Restaurant { constructor() { this.menu = []; this.categories = ['all']; } handleSearch(event) { const searchInput = document.querySelector('.search-input'); const minPriceInput = document.querySelector('.min-price'); const maxPriceInput = document.querySelector('.max-price'); if (event.target.matches('.search-btn')) { event.preventDefault(); const keyword = searchInput.value.toLowerCase(); const minPrice = minPriceInput.value || 0; const maxPrice = maxPriceInput || Infinity; let category = docuemnt.querySelector(".filter-active").dataset.id; let filteredMenu = []; if (category === this.categories[0]) { // categories[0] is "all"; filteredMenu = menu.filter(item => { return item.title.includes(keyword) && item.price >= minPrice && item.price <= maxPrice; }) this.renderMenu(filteredMenu); } else { filteredMenu = menu.filter(item => { return item.category === selectedCategory && item.title.includes(keyword) && item.price >= minPrice && item.price <= maxPrice; }) this.renderMenu(filteredMenu); } } } render() { const buttonsContainer = document.querySelector('.btn-container'); const searchButton = document.querySelector('.search-btn'); buttonsContainer.addEventListener('click', this.handleFilter.bind(this)); searchButton.addEventListener('click', this.handleSearch.bind(this)); this.setCategories(); this.renderButtons(); this.renderMenu(this.menu); } }
my document object is undefined inside the handleSearch method. Is it possible to solve this problem without placing all element variables outside the method? Even if I do so I have another variable "categories" which is using document object.
-
React-dnd multiple elements
I can make react-dnd drag easily having a single element to drag over however I have array of 4 fields I'd like to make draggable. In my example code down below it creates four boxes from mapping the array and each box has a className of 'element'. Which should make them all draggable however they won't move.
Here is my drag code:
const ELEMENT = 'element'; const [{ isDragging }, drag, dragPreview] = useDrag(() => ({ type: ELEMENT, collect: (monitor) => ({ isDragging: monitor.isDragging() }) }))
Here is my draggable element:
{FieldDetail.map((e,i) => <div key={i} ref={dragPreview} style={{ opacity: isDragging ? 0.5 : 1}}> <div className='element' ref={drag}></div> </div> )}
Any ideas? Do I need to do something more within the type or className?
-
Updating React state in nested setTimeout callbacks
Can someone please tell me what's wrong with this and why the state of the 'video variable' remains false? So, even after the h2 element has rendered and is visible (i.e. the state of the video variable has been updated to true), when I click and call the hideVideo function, the video state remains false? Many thanks.
export default function App() { const [message, showMessage] = useState(false); const [video, setVideo] = useState(false); let modalTimeout, videoTimeout; useEffect(() => { window.addEventListener("click", hideVideo); setupTimeouts(); return () => { clearTimeout(modalTimeout); clearTimeout(videoTimeout); }; }, []); const setupTimeouts = () => { modalTimeout = setTimeout(() => { showMessage(true); videoTimeout = setTimeout(() => { showMessage(false); setVideo(true); }, 4000); }, 2000); }; const hideVideo = () => { console.log(video); showMessage(false); if (video === true) { setVideo(false); } }; return ( <div className="App"> {message && <h1>Message</h1>} {video && <h2>Video</h2>} </div> ); }
-
One connection - multiple channels
I have 2 watchers, each one creates a socket connection. How to make one connection?
There is a solution to move the connection to the socket into a variable and pass it to Watchers? There is a comment in the code where the socket is connected.
Channels in watchers
export function* watchOnSocketBinanceRT() { while (true) { const { socketToken } = yield take(types.BINANCE_SOCKET_OPEN); const socket = yield call(socketConnectionBinance, socketToken); // Creates a new connection const channel = yield call(socketChannelBinanceRT, socket); if (socket.onopen) { yield put({ type: types.BINANCE_SOCKET_CONNECTED }); } yield fork(socketSendBinance, socket); yield fork(socketCloseBinance, socket); const { cancel } = yield race({ task: call(socketOnmessageBinance, channel), cancel: take(types.BINANCE_SOCKET_CLOSED), }); if (cancel) { buffersRT.flush(); channel.close(); } } } export function* watchOnSocketBinance() { while (true) { const { socketToken } = yield take(types.BINANCE_SOCKET_OPEN); const socket = yield call(socketConnectionBinance, socketToken); // Creates a new connection const channel = yield call(socketChannelBinance, socket); if (socket.onopen) { yield put({ type: types.BINANCE_SOCKET_CONNECTED }); } yield fork(socketSendBinance, socket); yield fork(socketCloseBinance, socket); const { cancel } = yield race({ task: call(socketOnmessageBinance, channel), cancel: take(types.BINANCE_SOCKET_CLOSED), }); if (cancel) { channel.close(); } } }
Socket connection
const socketConnectionBinance = socketToken => { return new Promise((resolve, reject) => { let socket; if (socketToken) { socket = new WebSocket(`${wsUrlBinance()}/${socketToken}`); } else { socket = new WebSocket(`${wsUrlBinance()}`); } socket.onopen = function () { resolve(socket); console.log('Binance connection opened'); }; socket.onerror = function (event) { reject(event); console.log('Binance socket error: ', event); }; socket.onclose = function (event) { if (event.wasClean) { console.log('Binance connection closed'); } }; }); };
Thanks for the help!
-
How to connect a Python ML model to a MERN webapp?
I want to display the charts and results of a LDA model I coded on Python using Gensim in a Webapp, I have tried both with Django and MERN (Express, Node.js) and I saw child_process.spawn() could be useful but I am not quite sure how to use that in my webapp.
-
About future of mustache.js and turbo360
1.How is future of mustache.js.Is it prefer than ejs? Is not learning mustache.js just wasting time? Is not mustache.js outdated tool? 2.What can you say about turbo360 platform? Is it not outdated?
-
How can I allow a user to download a file from a link in express?
I have a function that allows you to create a folder in the directory where the server is located, and upload files there And I'm trying to access them via a direct link, like this
http://localhost:5000/attachments/1618413024408--1.jpg
Because, the file is located here
But why can't I access it?
Cannot GET /attachments/1618413024408--1.jpg
-
How much time does it take to learn VIM editor?
I just switched to Linux, Ubuntu to be specific. And I watched some videos on Youtube telling learn vim for better speed and bla bla. well I started learning it. but I just wanna know how much time does it take to learn It to get used to it.
I'm practicing Vimtutor for last 2 to 3 days. but still don't feel like knowing it.
So Just wanna know if there is any better resource. I watched some tutorial but seems like they were not enough.
Also this is my first question. so if I did anything wrong tell me that as well.
Thanks.
-
How can I implement a custom code block button in react-quill toolbar
I am trying to implement a custom code block button to be inserted in react-quill, but I am not sure how to proceed. I know I need to implement a handler for the code block (I named it
code-block
) and then add a button with a class name as `ql-code-block, but how can I make the editor display specific code block's style using html and css?import React, { useState } from 'react'; import { useQuill } from 'react-quilljs'; import 'quill/dist/quill.snow.css'; // Add css for snow theme export default () => { const theme = 'snow'; const modules = { toolbar: { container: '#toolbar', handlers: { 'code-block': function () { console.log('Code-block'); <---- How to implement the handler here }, }, }, clipboard: { matchVisual: false, }, }; const placeholder = 'Compose an epic...'; const formats = ['size', 'bold', 'script']; const { quill, quillRef } = useQuill({ theme, modules, formats, placeholder, }); const [content, setContent] = useState(''); React.useEffect(() => { if (quill) { quill.on('text-change', () => { setContent(quill.root.innerHTML); }); } }, [quill]); const submitHandler = (e) => {}; return ( <div style={{ width: 500, height: 300 }}> <div ref={quillRef} /> <div id='toolbar'> <select className='ql-size'> <option value='small' /> <option selected /> <option value='large' /> <option value='huge' /> </select> <button className='ql-bold' /> <button className='ql-code-block' /> <button className='ql-script' value='sub' /> <button className='ql-script' value='super' /> </div> <div id='editor' /> <form onSubmit={submitHandler}> <button type='submit'>Submit</button> </form> </div> ); };
-
Not showing data from localStorage
I am using ReactJs for my project, and I'm using a rich text editor, when I write something in the content aria then I'm able to save data inside localStorage, but when I want to have data inside content body after refresh the whole page, It doesn't show data in the content aria but I have saved data succesfully in the localStorage
I don't know where is problem,
I have tried by this way:
const blogFromLS = () => { if (typeof window === "undefined") { return false; } if (localStorage.getItem("blog")) { return JSON.parse(localStorage.getItem("blog")); } else { return false; } };
const [body, setBody] = useState({ editorState: EditorState.createEmpty(), blogFromLS: blogFromLS(), }); const { editorState } = body; const onEditorStateChange = (editorState) => { setBody({ editorState }); formData.set( "body", draftToHtml(convertToRaw(editorState.getCurrentContent())) ); if (typeof window !== "undefined") { localStorage.setItem( "blog", JSON.stringify( draftToHtml(convertToRaw(editorState.getCurrentContent())) ) ); } };
<div className="form-group"> <Editor className="editorCustom" editorState={editorState} wrapperClassName="demo-wrapper" editorClassName="demo-editor" onEditorStateChange={onEditorStateChange} placeholder="write something..." // onChange={handleBody} // value={body} /> </div>
Any Suggestion please.