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.
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 :)
Hope this will helpfull
import React, { useEffect} from 'react';
import { connect } from 'react-redux';
export function UserIndex({users,userroles,getUsers,getUserRoles }){
// Load data on component mount
useEffect(() => {
getUsers({});
getUserRoles();
}, [getUserRoles, getUsers]);
console.log(users);
console.log(userroles);
return (
<></>
);
}
const mapState = (state) => ({
users: state.user.users,
userroles :state.listHelper.userroles,
});
const mapDispatch = (state) => ({
getUsers: (payload) => state.user.getUsers(payload),
getUserRoles : () => state.listHelper.getUserRoles(),
});
const UserIndexContainer = connect(mapState, mapDispatch)(UserIndex);
export default UserIndexContainer;