Search code examples
reactjsreduxdispatch

Rendering after dispatch in react-redux


I have one doubt with react-redux. The component must be rendered after finish fetching data. The current code returns always {}. How can I solve this issue?

function Category(props) {
  const [categories, setCategories] = useState([]);
  props.dispatch(categoryActions.fetch());
  useEffect( () => {
    setCategories(props.categories)
  }, [props]);

  return (
    <Container className={classes.root}>
        .....
    </Container>
  );
}

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

function mapDispatchToProps(dispatch) {
    return {
      dispatch,
    };
}

export default connect(mapStateToProps, mapDispatchToProps)(Category)

Solution

  • First, I have some questions:

    1. What does const [categories, setCategories] = useState([]); do?
      categories are provided as props to Category component by Connect.
      useState hook is used to define and control internal state.
      It's not conflicting technically since you can call them props.categories and categories respectively but there might be confusion.

    2. What actions do you want to dispatch in the component?
      mapDispatchToProps looks doing nothing. Have a look at their official example.