I'm trying to display my initial state from my store. I know my code is not correct but i'm hoping to learn the most simple method for this. Can I simply receive data from the store with props? or do I need some lifecycle event to target data in the store?
Here is my current attempt: I have edited this to include my reducer and I have updated my component as per the comments below.
//store .js
import { createStore, applyMiddleware,compose } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers'; //the index.js file
const initialState = {
}
const middleware = [thunk]
const store = createStore(
rootReducer,
initialState,
compose(
applyMiddleware(...middleware),
window.__REDUX_DEVTOOLS_EXTENSION__&& window.__REDUX_DEVTOOLS_EXTENSION__()
)
);
export default store;
Now when trying to map out my props in the below component, I get the error:
this.props.properties.map is not a function
//Properties component that renders a map of my props
import React, { Component } from 'react'
import PropTypes from 'prop-types';
import {connect} from 'react-redux';
import {getListings} from '../actions/postActions';
class Properties extends Component {
componentDidMount(){
getListings()
}
render() {
const properties = this.props.properties.map(property => (
<div key = {property.id}>
<h3>{property.propertyName}</h3>
<div style={{width: '4em', height:'4em', backgroundColor: 'blue'}}>image</div>
<p>{property.footage}</p>
<p>{property.address}</p>
<p>{property.price}</p>
</div>
))
return (
<div>
<h1>Current Listings</h1>
{properties}
</div>
)
}
}
Properties.propTypes = {
properties: PropTypes.array.isRequired,
newListing: PropTypes.object
}
const mapStateToProps = state =>({
properties: state.properties.properties,
newListing: state.properties.newListing
});
export default connect(mapStateToProps)(Properties)
//my actionsHandler.js
import {GET_LISTINGS, NEW_LISTING} from './types';
export function newProperty(formdata){
return function(dispatch){
dispatch({
type: NEW_LISTING,
payload: formdata
})
}
}
export function getListings(form){
return function(dispatch){
dispatch({
type: GET_LISTINGS,
})
}
}
//my reducer
import {NEW_LISTING, GET_LISTINGS} from '../actions/types';
const initialState={
properties: [
{
id: 1,
propertyName: 'The boogaloo',
footage: '3500 sqft',
address: '123 hill bounty rd',
price:'$ 350,000.00'
}
],
newListing: {}
}
export default function(state=initialState, action){
switch(action.type){
case NEW_LISTING:
return{
...state,
properties:state.properties.push(action.payload)
}
case GET_LISTINGS:
return{
state
}
default:
return state
}
}
initialStateappears to be an array, while object is required. Assuming your later attempt (unsuccessful for above reason) to accesspostsproperty, you should set your initial state to something, likeposts:[...], at least. Next, there's noitemsproperty in your state, so if you need to put your entire array intopropertiesprop of your component, you may want to keep it asproperties: store.posts.