Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

reset value after submitting data to API #5511

Closed
surjit opened this issue Sep 16, 2023 · 3 comments
Closed

reset value after submitting data to API #5511

surjit opened this issue Sep 16, 2023 · 3 comments
Labels

Comments

@surjit
Copy link

surjit commented Sep 16, 2023

Problem
I just want func call to reset editor value after data sent to API

Solution
There should something prop or other way to reset editor value

Alternatives
I tried using Transforms to remove all node, when it does not worked

Context

import React, {useCallback, useMemo} from "react";
import {withHistory} from "slate-history";
import {Editable, Slate, withReact} from "slate-react";
import {createEditor, Editor, Element as SlateElement, Range, Text, Transforms} from "slate";
import {css} from "@emotion/css/dist/emotion-css.cjs";
import {HoveringToolbar, toggleMark} from "./toolbar/hover";
import {BottomToolbar} from "./toolbar/bottom";
import Image from "./elements/Image";
import Link from "./elements/Link";
import {isKeyHotkey} from "is-hotkey";

const withImages = (editor: Editor) => {
    const {isInline, isVoid} = editor

    editor.isInline = element =>
        ['link'].includes(element.type) || isInline(element)

    editor.isVoid = element => {
        return element.type === 'image' ? true : isVoid(element)
    }

    return editor
}

const Element = (props: any) => {
    const {attributes, children, element} = props

    switch (element.type) {
        case 'image':
            return <Image {...props} />
        case 'link':
            return <Link {...props} />;
    }

    return <p {...attributes}>{children}</p>
}

const Reply = () => {
    const editor = useMemo(() => withImages(withHistory(withReact(createEditor()))), [])

    const renderElement = useCallback((props: any) => <Element {...props} />, [])

    const initialValue = useMemo(() => {
        const storedContent = localStorage.getItem('draft-b8yqzeig-1006');
        return storedContent ? JSON.parse(storedContent) : [{type: 'paragraph', children: [{text: ''}]}];
    }, [])


    const onKeyDown: React.KeyboardEventHandler<HTMLInputElement> = event => {
        const {selection} = editor
        if (selection && Range.isCollapsed(selection)) {
            const {nativeEvent} = event
            if (isKeyHotkey('left', nativeEvent)) {
                event.preventDefault()
                Transforms.move(editor, {unit: 'offset', reverse: true})
                return
            }
            if (isKeyHotkey('right', nativeEvent)) {
                event.preventDefault()
                Transforms.move(editor, {unit: 'offset'})
                return
            }
        }
    }

    const Leaf = ({attributes, children, leaf}: any) => {
        if (leaf.bold) {
            children = <strong>{children}</strong>
        }

        if (leaf.italic) {
            children = <em>{children}</em>
        }

        if (leaf.underlined) {
            children = <u>{children}</u>
        }

        return <span className={leaf.text === '' ? css`padding-left: 0.1px;` : null} {...attributes}>{children}</span>
    }

    const handleSubmit = () => {
        // after sending data to API,I want to reset content,
        // I tried all, even tried ChatGPT nothing worked
    }

    return <Slate
        editor={editor}
        initialValue={initialValue}
        onChange={value => {
            const isAstChange = editor.operations.some(
                op => 'set_selection' !== op.type
            )
            if (isAstChange) {
                // Save the value to Local Storage.
                const content = JSON.stringify(value)
                localStorage.setItem('draft-b8yqzeig-1006', content)
            }
        }}>

        <div className={css`max-height: calc(50vh - 90px); min-height:70px; overflow:auto`}>
            <HoveringToolbar/>
            <Editable
                renderElement={renderElement} className="compose-wrapper"
                renderLeaf={props => <Leaf {...props} />}
                placeholder="Enter some text..."
                onKeyDown={onKeyDown}
                onDOMBeforeInput={(event: InputEvent) => {
                    switch (event.inputType) {
                        case 'formatBold':
                            event.preventDefault()
                            return toggleMark(editor, 'bold')
                        case 'formatItalic':
                            event.preventDefault()
                            return toggleMark(editor, 'italic')
                        case 'formatUnderline':
                            event.preventDefault()
                            return toggleMark(editor, 'underlined')
                    }
                }}
            />
        </div>
        <button onClick={handleSubmit}></button>
    </Slate>
}
@surjit surjit added the feature label Sep 16, 2023
@blascokoa
Copy link

i set a useState variable that I pass to the Slate component, check if it changes with an use effect, and just remove all childrens and setup a new children with an empty message, this worked for me.

useEffect(() => {
    if (shouldReset !== undefined) {
      editor.removeNodes();
      editor.children = emptyMessage;
    }
  }, [shouldReset]);

@surjit
Copy link
Author

surjit commented Sep 22, 2023

It works thanks, @blascokoa

@surjit surjit closed this as completed Sep 22, 2023
@kaimiyang
Copy link

wish supply api method, @blascokoa, editor.children = somecontent , many times not work. I have to remount this editor.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants