beekai-oss / little-state-machine

📠 React custom hook for persist state management
https://lrz5wloklm.csb.app/
MIT License
1.48k stars 53 forks source link

state not up to date #139

Closed fini closed 2 years ago

fini commented 2 years ago

Yesterday I had an issue where I updated some state data, and I could see it was updated in the localStorage, but my state variable wasn't updating. I then had to use getState() in my function which worked. I always assumed the state variable would be up to date. Am I missing something? Code snippets below:

  const { actions, state, getState } = useStateMachine({
   // my actions here
  })
 // ---
  const doUpdateForm = useCallback(
    (fieldName, fieldValue, skipRender) => {
      actions.updateForm(
        {
          [fieldName]: fieldValue,
        },
        { skipRender }
      )
      // update form on server
      sendFormUpdate()
    },
    [actions]
  )
// ---
  const sendFormData = (data, mode = 'update') => {
    const currentState = getState() // does not work if i just supply state.form as data parameter.
   // ...
 }
bluebill1049 commented 2 years ago

state update will constantly be refreshed at the next re-render (same as useState), getState function is basically accessing the internal state directly which explains why it's working.

fini commented 2 years ago

state update will constantly be refreshed at the next re-render (same as useState), getState function is basically accessing the internal state directly which explains why it's working.

Thanks for your reply, I am using it to update every change in a React Hook Form on the server, and it seems I am not waiting until next re-render ;) So I will use getState() for this feature then. Thanks for your great work.

bluebill1049 commented 2 years ago

Glad you find getState useful. 🙏