reactjstypescriptnext.jssuneditor

State not updating in SunEditor onChange event


version

const SunEditor = dynamic(() => import("suneditor-react"), {
  ssr: false,
});
import "suneditor/dist/css/suneditor.min.css"; // Import Sun Editor's CSS File
// states
const [toggle, setToggle] = useState<boolean>(false);
const [content, setContent] = useState<string>("");
useState(() => {
  console.log(toggle, content);
}, [toggle, content]);
// render
return (
  <SunEditor
    onChange={(content) => {
      setToggle(!toggle);
      setContent(!content);
    }
  />
);

When I type the console panel always shows me that only content was changed, but toggle is not changed.

I really don't know what happens, I just want to set other states inside SunEditor's onChange event, but I can't. Can anyone just explain to me how to fix this?


Solution

  • You can use a function inside the setToggle function to get the current state value and return the modified value for that state variable.

    <SunEditor
        onChange={(content) => {
            setToggle((value) => !value);
            setContent(content);
        }
    />
    

    Due to the async nature of setState, passing in a function into the state setter instead of a value will give you a reliable way to get the component’s state. It's the recommended approach when setting state based on previous state.