#derived sianals issue

11 messages · Page 1 of 1 (latest)

gray hawk
#

my conponnent code is

export const AlertPanel: Component<{
  successMsg: Accessor<string>;
  errorMsg: Accessor<string>;
}> = ({ successMsg, errorMsg }) => {
  const showError = () => errorMsg() != "";
  const showSuccess = () => successMsg() != "";

  createEffect(() => {
    console.log(showError());
    console.log(showSuccess());
  });

  return (
    <>
      <Banner type="error" opened={showError()}>
        {errorMsg()}
      </Banner>
      <Banner type="success" opened={showSuccess()}>
        {successMsg()}
      </Banner>
    </>
  );
};

When the errorMsg changes, the showError does not change accordingly. Why is this happening?

hardy oxide
#

Do not destructure props

vale fossil
#

destructuring props loses reactivity. You could try something like this:

export type AlertPanelProps = {
  successMsg: string;
  errorMsg: string;
}

export const AlertPanel: Component<AlertPanelProps> = (props) => (
  <>
    <Banner type="error" opened={() => props.errorMsg !== ""}>
      {props.errorMsg}
    </Banner> 
    <Banner type="success" opened={() => props.successMsg !== ""}>
      {props.successMsg}
    </Banner> 
  </>
)

I'm not super confident on the exact syntax needed to check for preserving reactivity within the opened prop on <Banner /> but you could use show for solid-like control flow:

export const AlertPanel: Component<AlertPanelProps> = (props) => (
  <>
    <Show when={props.errorMsg}>
      <Banner type="error">{props.errorMsg}</Banner> 
    </Show>
    <Show when={props.successMsg}>
      <Banner type="success">{props.successMsg}</Banner> 
    </Show>
  </>
)
#

just make sure you pass the messages like
<AlertPanel successMsg={successMsg()} />

gray hawk
#

thanks a lot, i will check it

vale fossil
#

the biggest thing is that in general you should not destructure props

gray hawk
#

why destructure props will lost the reactivity?

#

is there some tech article to intro ?

chrome gorge
#

Props use getters to remain reactive.

#

Destructuring them evaluated the getters once, losing the reactivity afterwards.