简体   繁体   中英

Why Editor field not rendering recent data in react-hook-form

I'm using react hook form in modal popup and facing problem to render tinymce editor content in edit form. It is working fine when popup being open first time but it rendering old data when close that popup and open for other record.

Here is mycode:

import TextEditor from '../utils/Editor';

const EditData = props => {

    const uuid = uuidv4();

      const [templateData, setSubmittedTemplate] = useState({});

      const [formData, setFormData] = useState({
        subject: '',
        content: ''
      });

      const { subject, content} = formData;
      const {
        register,
        handleSubmit,
        control,
        errors,
        reset,
        setValue,
        getValues,
        formState: { isSubmitSuccessful }
      } = useForm({ resolver: yupResolver(schema), defaultValues: formData});
      
      const onUpdateData = async(values) => {
        //api to update
      };

      

      useEffect(() => {
          if(props.temp_id){
            api.get(`/api/data/${props.temp_id}`)
            .then(response => {
                setFormData(response.data);
                setValue('subject',response.data.subject);
                setValue('content',response.data.content);
            });
        }
      }, [props.temp_id, reset]);

      
    return (
        <Modal show={props.modalState} onHide={() => props.onHide('editData')}>
                <Form onSubmit={handleSubmit(onUpdateData)}>
                    <Modal.Header closeButton>
                        <div>
                            <Modal.Title>Edit</Modal.Title>
                        </div>
                    </Modal.Header>
                    <Modal.Body>
                        <Form.Row>
                            <Form.Group as={Col} controlId="subject">
                                <Form.Label className="floating-label">Subject</Form.Label>
                                <Form.Control type="text" name="subject" className="custom_input" ref={register}></Form.Control>
                                {errors.subject && <label className="error">{errors.subject?.message}</label>}
                            </Form.Group>
                        </Form.Row>

                        <Form.Row>
                            <Form.Group as={Col} controlId="content">
                                <Form.Label className="floating-label">Content</Form.Label>
                                <Controller
                                    control={control}
                                    name="content"
                                    defaultValue={formData.content}
                                    render={({ onChange, value}) => (
                                        <TextEditor onChange={onChange} initialvalue={value} register={register} />
                                    )}
                                />
                                 {errors.content && <label className="error">{errors.content?.message}</label>}
                            </Form.Group>
                        </Form.Row>

                    </Modal.Body>
                    <Modal.Footer>
                    <Button varient="primary" className="pl-4 pr-4" type="submit">Update</Button>
                    </Modal.Footer>
                </Form>
            </Modal>
    );
}

export default EditData;

TextEditor have tinyMCE configuration code:

const TextEditor = props => {

    return (
        <Editor
            className="custom_input"
            ref={props.register}
            initialValue={props.initialvalue}
            init={{
            height: 300,
            menubar: false,
            statusbar:false,
            //inline:true,
            plugins: [
                'advlist autolink lists link image charmap print preview anchor',
                'searchreplace visualblocks code fullscreen',
                'insertdatetime media table paste code'
            ],
            toolbar:
                'undo redo | formatselect | bold italic | placeholder | forecolor backcolor |  \
                alignleft aligncenter alignright alignjustify | \
                bullist numlist outdent indent | code | removeformat',
            setup: function (editor) {
                //
                }
            }}
            onEditorChange={props.onChange}

        />
    )
}
export default TextEditor;

Please let me know what is missing or something worng so that editor not updating recent data while other form field like subject working fine. Thanks.

You need to add two changes, the first one is that you need to wrap your onChange in a callback, secondly you should pass the value prop that comes from the Controller component as the value prop in the Editor, not the initialValue prop.

const TextEditor = props => {
 const handleEditorChange = (editor) => props.onChange(editor);

 return (
    <Editor
        className="custom_input"
        value={props.initialvalue}
        init={{
        height: 300,
        menubar: false,
        statusbar:false,
        //inline:true,
        plugins: [
            'advlist autolink lists link image charmap print preview anchor',
            'searchreplace visualblocks code fullscreen',
            'insertdatetime media table paste code'
        ],
        toolbar:
            'undo redo | formatselect | bold italic | placeholder | forecolor backcolor |  \
            alignleft aligncenter alignright alignjustify | \
            bullist numlist outdent indent | code | removeformat',
        setup: function (editor) {
            //
            }
        }}
        onEditorChange={handleEditorChange}

    />
 )
}

By doing that you can use the setValue function of react hook form in your useEffect to set the editor content. You also don't need to pass a register to the TextEditor component because the controller is handling your form state changes.

Here's a working sandbox to show you how it works: https://codesandbox.io/s/tinymce-react-demo-forked-gg7o8?file=/src/index.js

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM