fun joker
fun joker

Reputation: 1727

How to display data from redux store?

I have created action and reducer for saving messages (array) in redux store. I have created actions and reducer for it but how can I display data once it is stored in redux store ?

reducer.js:

import { SAVE_ITEMS, SAVE_MESSAGES} from '../actions/types';

const initialState = {
    messages: [],
    items: []
}

export default function (state = initialState, action) {
    switch (action.type) {
        case SAVE_MESSAGES:
            return {
                ...state,
                messages: action.payload
            };
        default:
            return state;
    }
}

action.js:

import { SAVE_MESSAGES } from './types';

export const saveMessages = (messages) => ({
    type: SAVE_MESSAGES,
    payload: { messages }
})

In component I am saving data like this:

this.props.saveMessages(data)

and also the connect:

const mapStateToProps = state => ({
    author: state.chat.author,
    messages: state.chat.messages,
    message: state.chat.message
})

export default connect (mapStateToProps, { saveAuthor, saveMessages, deleteAuthor, deleteMessage })(Chat); 

In combineReducer i.e index.js:

import {combineReducers} from 'redux';
import users from './loginReducer'
import allusers from './userReducer'
import chatReducer from './chatReducer'

export default combineReducers({
    users: users,
    allusers: allusers,
    chat: chatReducer
})

Now if I do console.log(this.props) see screenshot below:

enter image description here

Now if I do console.log(this.props.messages) see screenshot below:

enter image description here

Now I want to map over messages data and display it but I am getting error if I do this.props.messages.messages[0] -> error this.props.messages[0] gives undefined.

Screenshot: (redux tools)

enter image description here

Upvotes: 1

Views: 2657

Answers (1)

Triyugi Narayan Mani
Triyugi Narayan Mani

Reputation: 3109

I think first you can check if this.props.messages.messages is not undefined and then you can use map() to print messages like this:

{this.props.messages && this.props.messages.messages && this.props.messages.messages.map(function(msg,i) {
    return (
        <p>{msg.message}</p>
    )
})}

Upvotes: 1

Related Questions