nodecg / react-hooks

React Custom Hooks for NodeCG
MIT License
20 stars 12 forks source link

useReplicant default value unable to set, causing updated project to fail to load. #277

Closed DrEVILish closed 4 months ago

DrEVILish commented 4 months ago

Giving a simple example of what I'm trying to do:

function Timing() {
  const [count, setCount] = useReplicant("counter");
  return (
    <div>
      <div>{count.length}</div>
      <button onClick={() => setCount([count[0] + 1])} />
    </div>
  );
}

setCount returns an array containing a cell containing the number 1.

I'm getting Cannot read properties of undefined (reading 'length') I understand where this is coming from.

I've tried setting setCount([]) directly after the const = ... before the return (...)

I tried what previously worked const [count, setCount] = useReplicant("counter", []); I'm not sure what the correct way to set this up is, it worked previously before doing a dependency and node update.

Totally understand this is in ALPHA and asking questions is probably not helpful, but as a point of feedback, If I can't set a default value or object it's a bit useless.

I read through the src of useReplicant and couldn't workout the new way to pass in a default value/object to the Rep.

Node20 - LTS react - 18 nodecg - latest @nodecg-react-hooks - latest

happy to list any thing else needed but I believe these are the minimum required to cause an error.

Hoishin commented 4 months ago

You need to handle the case when count is undefined. Replicant value can always be undefined and you should handle that case whether you have default value.

DrEVILish commented 4 months ago

Thanks for the super quick reply.

I think previously it declared "count" as an Array and was synchronous/blocking, I think the new is provided async style. Following worked for me.

function Timing() {
  const [count, setCount] = useReplicant("counter", {
    defaultValue: [0],
    persistent: false,
  });
  console.log(typeof count);
  if (typeof count === "undefined") {
    return;
  }
  return (
    <div>
      <div>
        {count[0]} {count.length} {typeof count}
      </div>
      <button onClick={() => setCount([count[0] + 1])} />
    </div>
  );
}