Reputation: 102
I'm making this application with react, redux and axios where one component shows a full list of addresses and the next shows one selected address. The address listing component work fine but there's something wrong with the single view component which returns the following error:
somewhere in the redux chain involving changeSelected->address there is a promise being sent instead of the promised results. I'm having a hard time pinpointing this as I've used a similar structure for the multi address view fetchAddresses -> addresses which works fine.
here's my react component
const Card = async (props) => {
const { changeSelected,address } = props
console.log(address)
useEffect(() => {
changeSelected(1);
},[changeSelected(1)])
if (!address){
return <h1>No results</h1>
} else {
return (
<React.Fragment>
<CssBaseline />
<Container maxWidth="sm">
<Typography component="div" style={{ backgroundColor: '#cfe8fc', height: '100vh' }} >
<Typography variant="h6" >{address.body}</Typography>
</Typography>
</Container>
</React.Fragment>
);
}
}
Card.propTypes = {
changeSelected: PropTypes.func.isRequired,
address: PropTypes.object.isRequired,
}
const mapStateToProps = state => ({
address: state.address.address,
})
export default connect(mapStateToProps, {changeSelected})(Card)
here is my dispatched action
export const changeSelected = (postData) => dispatch => {
console.log(postData)
axios.get(`https://jsonplaceholder.typicode.com/posts/${postData}`)
.then(addresses => {
console.log(addresses)
dispatch({
type: CHANGE_SELECTED,
payload: addresses.data
})}).catch(err => {
dispatch({
//if there's an error, send the user a card saying so
type: CHANGE_SELECTED,
payload: [{id:0,nickName:'error',content:'please contact cutomer service at 010-314-1150'}]
})
console.log(err)
})
}
and here is my reducer
//create initial state
const initialState = {
addresses: [],
address:{}
}
export default (state = initialState, action) => {
switch(action.type) {
case FETCH_ADDRESSES:
return{
...state,
addresses: action.payload
}
case CHANGE_SELECTED:
return{
address: action.payload
}
default:
return state
}
}
the response is making it to the reducer but the error message is being called before a promise is returned.
Upvotes: 0
Views: 75
Reputation: 102
It turns out the problem was designating my react component (Card) as "async". got rid of that and it worked fine.
Upvotes: 1