0

I am quite new to React and stumped on the best way to implement a form with the need for persistent storage of some filters. There are 10 different categories in the form, and each category has a different set of filters that need to be persisted independently across the application upon submitting the form. I am using const [storedFilter, setStoredFilter] = useAtom(selectedAtom); to access and set the filters. However, since the category is only determined on submission of the form, I am unable to determine what selectedAtom is beforehand. From what I understand, hooks should also not be called/ initialised in event handlers. What is the best way to implement this (not sure if I would need to create 10 separate hooks in advance)? Any advice would be much appreciated!

m-00
  • 41
  • 5

1 Answers1

0

If selectedAtom is expected to be determined at a later stage, you should create a new state variable for it.

const [selectedAtom, setSelectedAtom] = useState(); // pass initial value, if any

const [storedFilter, setStoredFilter] = useAtom(selectedAtom);

// event handler
const eventHandler = (evt) => {
  setSelectedAtom(newValue); // derive newValue from event
};

I assume useAtom hook updates storedFilter based selectedAtom passed as argument.

Vaibhav Nigam
  • 1,334
  • 12
  • 21
  • Thank you, that is really insightful! I tried it and it works, but it takes some time before the selectedAtom is updated. I'm not sure if there is an easier and cleaner way than using useEffect. – m-00 Aug 09 '23 at 12:42
  • @m-00 It totally depends on your implementation of event handler. Without looking at code, I cannot comment on its performance. If you think my answer worked for you and you have no more questions, you may accept my answer. :) – Vaibhav Nigam Aug 09 '23 at 14:07