user11940251
user11940251

Reputation:

redux hooks for functional component

https://codesandbox.io/s/boring-wu-btlre

function useHackerNews(props) {
  const hackerNews = useSelector(state.channel);

  const dispatch = useDispatch();
  return (
    <button
      onClick={() => {
        getPosts(channel);
        getAlert();
      }}
      className="btn btn-primary btn-lg btn-block"
    >
      Get top news
    </button>
  );
}

Upvotes: 0

Views: 127

Answers (2)

Asaf Aviv
Asaf Aviv

Reputation: 11800

useSelector takes a function with the state of redux store as a parameter, use the state of the store to return the desired data

const hackerNews = useSelector(state => state.channel);

Here's the updated codesandbox: https://codesandbox.io/s/jolly-faraday-9eyk5

Upvotes: 0

Max
Max

Reputation: 519

basically you convert ´mapStateToProps´ using ´useSelector´

So this:

const mapStateToProps = state => ({ channel: state.channel });

Becomes:

const channel = useSelector(state => state.channel);

Your ´mapDispatchToProps´ is converted using ´useDispatch´

So you can convert:

const mapDispatchToProps = { getPosts: fetchPosts, getAlert: displayAlert };

To:

const getPosts = () => useDispatch(fetchPosts());
const getAlert = () => useDispatch(displayAlert());

Hope that makes sense!

Upvotes: 1

Related Questions