0

Using React, I am writing code for a plugin that uses local storage or session storage depending on the application that is calling it. It is set up by passing in optional parameters to the component that default to local storage. If our web service is using the plugin, it passes the session storage methods in. Due to constraints, our desktop app doesn't pass in the parameters, and so we default to local storage within the component.

export function myComponent(optionalParameter?: string, storeOptionalParameter?: (selection: string) => void) {
    const [variable, storeVariable] = optionalParameter && storeOptionalParameter
        ? [optionalParameter, storeOptionalParameter]
        : useLocalStorage<string>('storageName', 'default');
}

I know this is breaking the rules of hooks. Technically, it compiles and runs just fine, since every render will be dependent on the environment it is rendered in. I'd still like to find a better way to accomplish this so my linter will stop complaining about it.

1 Answer 1

1

Why not just wrap the component.

function Component({variable, storeVariable}) {
  ...
}

function ComponentThatUsesStore() {
  const [variable, storeVariable] = useLocalStorage<string>('storageName', 'default');
  return (<Component variable={variable} storeVariable={storeVariable} />)
}

function ParentComponent(...) {
   if (optionalParameter && storeOptionalParameter) {
     return (
       <Component
         variable={optionalParameter}
         storeVariable={storeOptionalParameter}
       />
     );
   }
   return <ComponentThatUsesStore />;
}
Sign up to request clarification or add additional context in comments.

1 Comment

I ended up with a similar solution. The component is called from two places, one of which it is already wrapped. I was able to just call each storage type and pass them in to each component as necessary. Something I should've seen sooner, but your solution got me there.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.