Getting the state with rematch

923 Views Asked by At

I am learning rematch/redux. I can't get the state to show with the API. I have the model imported in index.js along with the store and the provider. These are my reducers/effects:

import { getItems } from './service'

const products = {
  state: {
    products: [],
  },

  reducers: {
    setProducts(state, products) {
      return {
        ...state,
        products,
      };
    },
  },
  effects: {
    async loadProducts() {
      const products = await getItems() // <-- This is the api working normally
      this.setProducts(products)
    },
  }

}

export default products

And this is my component:

import './App.css';
import { connect } from 'react-redux';
import React, { useEffect } from 'react';

const mapStateToProps = ({ products }) => {
  return {
    ...products
  }
}

const mapDispatchToProps = ({ products }) => {
  return {
    ...products
  }
}

const App = ({ products }) => {

  useEffect(() => {
    console.log(products)
  })

  return (
    <div className="App">
      {console.log(products)}
    </div>
  )
}

export default connect(mapStateToProps, mapDispatchToProps)(App);

I am not sure what I am missing.

Thank you.

2

There are 2 best solutions below

1
On

I'm Rematch maintainer, you should review our documentation or consider buying the official Redux made easy with Rematch book where you'll learn all this questions.

I highly recommend using React-Redux hooks instead of connect method.

import './App.css';
import { useSelector, useDispatch } from 'react-redux';
import React, { useEffect } from 'react';

const App = () => {
  const dispatch = useDispatch();
  const { products } = useSelector(rootState => rootState.products)
  useEffect(() => {
    dispatch.products.loadProducts();
  }, []);

  return (
    <div className="App">
      {console.log(products)}
    </div>
  )
}

export default App;

Be careful with hooks, you're forgetting to add the deps array to useEffect, any code you add there will run infinitely

Your Rematch models looks fine, you just need to work more on React essentials :)

0
On

Redux rematch

  1. Create music listing app using youtube api
  2. How to create folder structure and setup store for react redux

Working code sandbox link

https://codesandbox.io/s/rematch-yf77l0?file=/src/pages/musics/index.jsx