Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

setUrl parameter to change the url on the fly #15

Closed
wants to merge 2 commits into from

Conversation

martunta
Copy link

In my project, I need to change the image dynamically, not just statically set it at the initialization of the component. For that, I added setUrl parameter that can be used in useEffect calls across the component.

Probably the same problem can be solved by composition, but this felt cleaner.

@lavrton
Copy link
Member

lavrton commented Jul 19, 2020

Thanks for your suggestion, but I don't think it should be a part of the lib. It is too simple to implement it by using the lib.

function AnotherApp() {
  const [url, setUrl] = React.useState(initialURL);
  const [image, status] = useImage(url);
  React.useEffect(function(){
    // at some condition
    setUrl(anotherUrl);
  }, [setUrl]);

  return (
    <Image image={image} />
  );
}

Or you can just write your own hook:

const useSetImage = (initialURL) => {
   const [url, setUrl] = React.useState(initialURL);
   const [image, status] = useImage(url);
   return [image, status, setUrl];
}

function AnotherApp() {
  const [image, status, setUrl] = useSetImage(initialURL);

  React.useEffect(function(){
    // at some condition
    setUrl(anotherUrl);
  }, [setUrl]);

  return (
    <Image image={image} />
  );
}

@lavrton lavrton closed this Jul 19, 2020
@martunta
Copy link
Author

oh, I thought that initial value is set only during first render. https://reactjs.org/docs/hooks-rules.html. and now I realize that this might only apply to useState. will try it out, thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants