Naterz
Naterz

Reputation: 437

transitioning to use redux with hooks

figuring out how to use redux with hooks using this way but not sure its the correct way

import React, { useState, useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { getPins } from "../../../actions/pins";

function MainStory() {
  const pins = useSelector(state => state.pins.pins);
  const dispatch = useDispatch();
  useEffect(() => {
    dispatch(getPins(pins));
  }, []);
  console.log(pins);
return(<div> test </div>

would the above way be the right way to go despite missing dependencies?

React Hook useEffect has missing dependencies: 'dispatch' and 'pins'. Either include them or remove the dependency array

with components (the way i had it before)

import { getPins } from "../../actions/pins";
import { connect } from "react-redux";
import PropTypes from "prop-types";
export class Pins extends Component {
  static propTypes = {
    pins: PropTypes.array.isRequired,
    getPins: PropTypes.func.isRequired
  };
  componentDidMount() {
    this.props.getPins();
  }
  render() {
    console.log(this.props.pins);
    return <div>test</div>;
  }
}
const mapStateToProps = state => ({
  pins: state.pins.pins
});

export default connect(mapStateToProps, { getPins })(Pins);

the plan is to list each pin

Upvotes: 1

Views: 257

Answers (1)

Ori Drori
Ori Drori

Reputation: 191946

You can add dispatch to the dependencies list, since it won't change. If you'll add the pins to dependancies list of the useEffect block, you might cause infinite loop, if the response to the action changes the state (call to server that returns an array).

However, according to the class component example, the getPins() action creator doesn't require the value of pins, so you can just add dispatch to the list of dependancies:

function MainStory() {
  const pins = useSelector(state => state.pins.pins);
  const dispatch = useDispatch();
  useEffect(() => {
    dispatch(getPins());
  }, [dispatch]);
  console.log(pins);
return(<div> test </div>

Upvotes: 3

Related Questions