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

React duplicates tags #834

Closed
banderazz opened this issue Jun 6, 2021 · 5 comments
Closed

React duplicates tags #834

banderazz opened this issue Jun 6, 2021 · 5 comments

Comments

@banderazz
Copy link

Hi!

There is some unexpected behavior I've exprerienced. Here is the code:

export const Prefixes = ({
  value,
  onChange,
}) => {
  const tagifyRef = useRef()
  const handleOnChange = (event) => {
    const tagifyInstance = tagifyRef.current;
    const prefixes = tagifyInstance.value.map(prefix => prefix.value);
    onChange(prefixes);
  }
  return (
    <Wrapper>
      <Tags 
        tagifyRef={tagifyRef}
        value={value.join(',')}
        onChange={handleOnChange}              
      />
    </Wrapper>
  )
}

So then I adding a new tag, it adds in input field and my value variable updates simultaneously and adds new tag in field as well. So I have two equal tags added. How can I prevent this?

Thanks!

@myteax
Copy link

myteax commented Jun 11, 2021

Let me help you, how can i reproduce this?

@yairEO
Copy link
Owner

yairEO commented Jun 11, 2021

You are using Tagify as a controlled component, which it isn't:

  1. Already discussed here: Controlled component behavior in React wrapper #489 (comment)
  2. What is a controlled react component

Do not re-feed the value back to Tagify - it handles the value by itself. only save it in your database when the onChange event fires

@yairEO
Copy link
Owner

yairEO commented Jun 11, 2021

Here's an example:

https://codesandbox.io/s/tagify-react-issue-template-forked-drwq4?file=/src/index.js

As you can see, the devaultValue prop should be used and not the value and in this case you won't get an endless cycle, where the value is changed, and Tagify triggers the onChange event listener, and then it itself changes value again (regardless it's the exact same value...)

@yairEO
Copy link
Owner

yairEO commented Jun 11, 2021

in the new release about to be push this will be addressed in the README and also code changes were made to allow setting the value prop itself and internally Tagify will compare if the value really did change or not, to prevent an infinite loop

@yairEO
Copy link
Owner

yairEO commented Jun 12, 2021

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

No branches or pull requests

3 participants