0
const [childData, setChildData] = useState({} as editorDataType);
  const [state, updateState] = useReducer((state: any, updates: any) => ({ ...state, ...updates }), {});

Tried with useState:

const getEditorData = (editorData: editorDataType) => {
  console.log(' editorData', editorData); //logs {content: 'test'}
  setChildData((prevData: any) => ({
    ...prevData,
    ...editorData
  }));
  console.log('getEditorData:: childData: ', childData); //prints empty object
}

Tried with use reducer:

const getEditorData = (editorData: editorDataType) => {
  console.log(' editorData', editorData); //logs {content: 'test'}
  updateState({ content: editorData.content })
  console.log('getEditorData:: state: ', state); //prints empty object
}
kittu
  • 6,662
  • 21
  • 91
  • 185
  • 3
    What's the question? If you're just wondering why the log statements show the old state, [see this question](https://stackoverflow.com/questions/54069253/the-usestate-set-method-is-not-reflecting-a-change-immediately) or [this documentation](https://react.dev/reference/react/useState#ive-updated-the-state-but-logging-gives-me-the-old-value) – Nicholas Tower May 30 '23 at 11:26
  • Does this answer your question? [The useState set method is not reflecting a change immediately](https://stackoverflow.com/questions/54069253/the-usestate-set-method-is-not-reflecting-a-change-immediately) – David May 30 '23 at 11:33
  • Because the scope of `getEditorData` knows about the current state or initial state in this case. JavaScript can't predict what's the state gonna be updated into. Try moving the `console.log` out of `getEditorData`, at the top scope inside your component. – Aleksandar May 30 '23 at 11:41

0 Answers0