Deno Fresh initialState mirroring state

32 Views Asked by At

I am getting strange behavior from my Deno Fresh application. I am confident it is a hydration issue, but I still do not understand why I am getting it. I would like to avoid a cheap workaround if possible.

Basically, my initialState variable changes with my state variable in the useState hook. When I first load the page, if I change selectedLevel, the object I used to instantiate the state for some reason mirrors the state, until I perform some other "hook-like" action.

// islands/EditUserForm.tsx
import {useUserForm} from "./UserForm.tsx";

export const EditUserForm = ({sessionId, roleResponse, initial}: EditUserFormProps) => {
  const {userData, ...otherData} = useUserForm<EditUserProps>({initial, ...na});

  const getUpdateUserProps = (data: EditUserProps): UpdateUserRequest[] => {
    if (userData.selectedLevel !== initial.selectedLevel){
      // ...do level has changed stuff
    } else {
      console.log(userData.selectedLevel, ' = ', initial.selectedLevel)
      // Console will print "<level>" = "<level>" without reloading the page
      // e.g. when I load the page, I will see "Reader = Reader" in the console
      // if I change it to "Writer", "Writer = Writer" will be printed to the console
    }
  }
...
  return (
    <div>
      ...
      <RoleSelect onChange={onRoleChange} levelOptions={levelOptions} selectedLevel={userData.selectedLevel}/>
      ...
    </div>
}

Where in islands/UserForm.tsx:

import { useState } from "preact/hooks";

export const useUserForm = <P extends UserProps>({initial, ...restProps}: useUserFormProps<P>): useUserFormType<P> => {
  const [userData, setUserData] = useState<P>(initial);
  ...
}

I get the expected behavior after I change a different property in the userData state, where the difference is registered and the initial no longer changes with userData

I can add a useEffect hook in the component to hydrate, but I am concerned about how variables are used if variable handed directly from a route can appear to be changing. Any clarity is much appreciated!

0

There are 0 best solutions below