I'm building a site useing graphql and apollo with a react front end. I have created a page where the site admin can update the content for particular sections of pages and it works, but I keep getting the error in the console: Component is changing a controlled input to be uncontrolled...
I'm also using ReactQuill wysiwyg editor. I thought that might be the problem but I remved it and I'm still getting the same error.
Here is the code for the content update page:
import { useState, useEffect } from 'react';
import { useMutation, useQuery } from '@apollo/client';
import { useNavigate, useParams } from 'react-router-dom';
import { GET_CONTENT_BY_ID } from '../../utils/queries';
import { UPDATE_CONTENT } from '../../utils/mutations';
import Form from 'react-bootstrap/Form';
import Button from 'react-bootstrap/Button';
import ReactQuill from 'react-quill';
import 'react-quill/dist/quill.snow.css';
const Content = () => {
const { id } = useParams();
const { loading, data } = useQuery(GET_CONTENT_BY_ID, {
variables: { id: id },
});
const [contentHead, setContentHead] = useState('');
const [contentText, setContentText] = useState('');
useEffect(() => {
const content = data?.contentById || {};
if (content) {
setContentHead(content.contentHead);
setContentText(content.contentText);
}
}, [data, setContentHead, setContentText]);
const [updateContent, { error }] = useMutation(UPDATE_CONTENT);
const navigate = useNavigate();
const submitHandler = async (e) => {
e.preventDefault();
try {
const { data } = await updateContent({
variables: {
id,
contentHead,
contentText,
},
});
navigate('/_admin');
} catch (error) {
console.log(error);
}
};
return (
<Form onSubmit={submitHandler}>
<Form.Group className="mb-3" controlId="contentHead">
<Form.Label>Section Heading</Form.Label>
<Form.Control
value={contentHead}
onChange={(e) => setContentHead(e.target.value)}
required
/>
</Form.Group>
<Form.Group className="mb-3" controlId="contentText">
<Form.Label>Text</Form.Label>
<ReactQuill
name="contentText"
value={contentText}
theme="snow"
onChange={setContentText}
/>
</Form.Group>
<Button type="submit">Submit</Button>
</Form>
);
};
export default Content;
In the ReqctQuill I tried onChange={(e) => contentText(e.target.value)} but there wasn't any change. The way it is now is what I got from, I think, their git repository.
I found an answer in another question on here. It wasn't the accepted answer but it works to get ride of the error.
A component is changing an uncontrolled input of type text to be controlled error in ReactJS
So for my form I change value={contentHead} and value={contentText} to value={contentHead || ''} and value={contentText || ''} and that works and gets rid of the error!