I want to display a list of components on the page and I am using react-redux for that. There are lots of boilerplates that are not clear and I am mixing those to reach some functionality. There is a problem with the async action throwing the following error
Actions must be plain objects. Use custom middleware for async actions.
action
export const fetchPublicDisplays = () => async dispatch => {
console.log("object")
const response = await api.get('/display/list');
dispatch({ type: FETCH_PUBLIC_DISPLAYS, payload: response.data });
};
reducer
const displayReducer = (state = [], action) => {
switch (action.type) {
case FETCH_PUBLIC_DISPLAYS:
return action.payload;
default:
return state
}
}
The component
class PublicHome extends React.Component {
componentDidMount() {
this.props.fetchPublicDisplays()
}
renderDisplays() {
console.log(this.props)
if (this.props.displays) {
return this.props.displays.map(display => {
return (
<div className="item" key={display.id}>
display
</div>
)
})
}
}
render() {
return (
<>
{this.renderDisplays()}
</>
)
}
}
const mapStateToProps = state => {
return { displays: state.deisplays };
};
export default connect(
mapStateToProps,
{ fetchPublicDisplays }
)(PublicHome);
Second argument to connect is a function(mapDispatchToProps) which gets dispatch as argument and returns an object. Here is the official doc for the same - https://react-redux.js.org/using-react-redux/connect-mapdispatch. In your case you are giving it an object i.e. fetchPublicDisplays. Second issue is you cannot do async things inside redux actions, you need to do the async operation first and then call the redux action to update the store state. Here is your modified code which should work -
import React from "react";
import { connect } from "react-redux";
import api from "axios";
export const displayReducer = (state = [], action) => { switch (action.type) {
case "FETCH_PUBLIC_DISPLAYS":
return action.payload;
default:
return state; } };
export const fetchPublicDisplays = (data) => (dispatch) => {};
class PublicHome extends React.Component { componentDidMount() {
this.fetchPublicDisplaysAsync(); }
fetchPublicDisplaysAsync = async () => {
const response = await api.get("/display/list");
this.props.fetchPublicDisplays(response.data); };
renderDisplays() {
console.log(this.props);
if (this.props.displays) {
return this.props.displays.map((display) => {
return (
<div className="item" key={display.id}>
display
</div>
);
});
} }
render() {
return <>{this.renderDisplays()}</>; } }
const mapStateToProps = (state) => { return { displays: state.deisplays }; };
const mapDispatchToProps = (dispatch) => ({ fetchPublicDisplays: (data) => {
dispatch({ type: "FETCH_PUBLIC_DISPLAYS", payload: data }); } });
export const App = connect(mapStateToProps, mapDispatchToProps)(PublicHome);
Here is the codeSandbox link for the same - https://codesandbox.io/s/distracted-meadow-3qi32?file=/src/App.js:0-1243