'Can't find the way to useSelector from redux-toolkit within event handler and pass params to it

There is an event handler for click and when it triggered i want to pull specific data from redux using selector where all logic many-to-many is implemented. I need to pass id to it in order to receive its individual data. Based on rules of the react the hooks can be called in function that is neither a React function component nor a custom React Hook function.

So what is the way to solve my problem ?

const handleMediaItemClick = (media: any): void => {
    // For example i check media type and use this selector to pull redux data by id
    const data = useSelector(playlistWithMediaSelector(imedia.id));
};


Solution 1:[1]

As stated in the error message, you cannot call hooks inside functions. You call a hook inside a functional component and use that value inside the function. The useSelector hook updates the variable each time the state changes and renders that component.

Also, when you get data with useSelector, you should write the reducer name you need from the redux state.

 const CustomComponent = () => {
      // The data will be updated on each state change and the component will be rendered
      const data = useSelector((state) => state.REDUCER_NAME);

      const handleMediaItemClick = () => {
          console.log(data);
      };
 }

You can check this page for more information.https://react-redux.js.org/api/hooks#useselector

Solution 2:[2]

You should probably use local state value to track that.

const Component = () => {
  const [imediaId, setImediaId] = useState(null);

  const data = useSelector(playlistWithMediaSelector(imediaId));

  function handleMediaClick(id) {
    setImediaId(id)
  }

  useEffect(() => {
    // do something on data
  }, [imediaId, data])

  return <div>...</div>
}

Does that help?

EDIT: I gather that what you want to do is to be able to call the selector where you need. Something like (considering the code above) data(id) in handleMediaClick. I'd bet you gotta return a curried function from useSelector, rather than value. Then you would call it. Alas, I haven't figured out how to that, if it's at all possible and whether it's an acceptable pattern or not.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ?brahim Akar
Solution 2