React Redux -> Map is not a function?

946 views Asked by At

So I am learning how to use redux and redux persist and currently I stuck at a problem right now. Whenever I try to map my store's content, it throws an error saying TypeError: tasks.map is not a function and I don't really know why the problem is occuring. I've googled around and tried debugging it, also tried to re-write the code a couple of time but it was all to no avail. Here's my entire code: rootReducer.js

import React from 'react'

let nextToDo = 0;
const task=[
    {
    }
]
const reducer =(state=task, action)=>
{
    switch(action.type)
    {
        case 'add':
            return[
                ...state,
                {
                    name: 'new',
                    id: nextToDo+=1
                }
            ]
        default:
            return state;
    }
}


export default reducer

store.js

import reducer from './rootReducer'
import {applyMiddleware,createStore} from 'redux'
import logger from 'redux-logger'
import {persistStore, persistReducer} from 'redux-persist'
import storage from 'redux-persist/lib/storage'

const persistConfig ={
    key: 'root',
    storage
}
export const persistedReducer = persistReducer(persistConfig, reducer)
export const store = createStore(persistedReducer, applyMiddleware(logger));
export const persistor = persistStore(store);

export default {store, persistor}

Index.js:

import React, {Component} from 'react'
import {createStore} from 'redux'
import reducer from './rootReducer'
import 'bootstrap/dist/css/bootstrap.min.css'
import {Button} from 'react-bootstrap'
import {store} from './store'
import {connect} from 'react-redux'

class Index extends Component {
    render(){
    const {tasks} = this.props
    const add=()=>
    {
        store.dispatch(
            {
                type: 'add', 
            }
        )
    }
    store.subscribe(()=>console.log('your store is now', store.getState()))
    return (
        <div>
            {tasks.map(task=><div>{task.name}</div>)}
            <Button onClick={()=>add()}></Button> 
        </div>
    )
}
}
const mapStateToProps=(state)=>
{
    return{
        tasks: state
    }
}

export default connect(mapStateToProps)(Index)
1

There are 1 answers

3
Eylon Shmilovich On BEST ANSWER

Try to declare state this way:

state = {
  tasks: [{}]
}

Then, on Index.js, you can pass it to props by doing this:

const mapStateToProps=(state)=>
{
    return {
        tasks: state.tasks
    }
}

And use it inside the Component with props.tasks