Reputation: 147
So I am making a to-do list in React in order to learn redux and I've been wondering how can I use something like the map function to map over the state, so that I can show the data stored within in different divs? here's my initialState:
const tasks=
[
]
And then there's my reducer:
const taskReducer = (state=tasks,action) =>
{
switch(action.type){
case 'addTask':
return[
...state,
{
id: nextToDo+=1,
text: action.text,
completed: false
}
]
default:
return state;
}
}
What I want to do is something among the lines of:
{tasks.map(task=>
<div>
<h1>{task.text}</h1>
<div>)}
But it doesn't really work, what are some ways I can accomplish this?
Upvotes: 2
Views: 3130
Reputation: 147
I found the solution people, here's the deal, I had to use mapStateToProps. I also had to change from functional to class component. So basically I first split my app in seperate files, one for the reducers and one for the store, here are all my files:
App.js:
import React from 'react';
import './App.css';
import tasksApp from './tasksApp';
import {Provider} from 'react-redux'
import store from './store'
function App() {
return (
<div>
<Provider store={store}>
<tasksApp></tasksApp>
</Provider>
</div>
);
}
export default App;
TasksApp.js:
import React, {Component} from 'react'
import 'bootstrap/dist/css/bootstrap.min.css'
import {Button} from 'react-bootstrap'
import {connect} from 'react-redux'
import $ from 'jquery'
import store from './store'
class tasksApp extends Component {
render(){
console.log(this.props)
const {tasks} = this.props
let nextToDo = 0;
const addTask=()=>
{
store.dispatch({
type: 'addTask',
text: $('.form-control').val()
})
}
return (
<div>
<h1>Enter Task</h1>
<input className='form-control' placeholder='Enter task'></input>
<Button variant='success' onClick={()=>addTask()}>Add Task</Button>
{tasks.map(task=>
<div key={task.id}>
<h1>{task.text}</h1>
<h2>{task.id}</h2>
<h3>{task.completed}</h3>
</div>)}
</div>
)
}
}
const mapStateToProps=(state)=>
{
return{
tasks: state
}
}
export default connect(mapStateToProps)(tasksApp)
store.js:
import {createStore} from 'redux'
import taskReducer from './reducers'
const store = createStore(taskReducer)
store.subscribe(()=>
console.log('Your store is now', store.getState())
)
export default store
reducers.js:
import store from './store'
import $ from 'jquery'
let nextToDo = 0;
const tasks=
[
{
id: nextToDo+=1,
text: 'action.text',
completed: false
}
]
const taskReducer = (state=tasks,action) =>
{
switch(action.type){
case 'addTask':
return[
...state,
{
id: nextToDo+=1,
text: $('.form-control').val(),
completed: false
}
]
default:
return state;
}
}
export default taskReducer;
Upvotes: 0
Reputation: 521
You also use redux connect()
method.
You can export default connect(mapStatetoProps)
for moreInfo:https://react-redux.js.org/api/connect
Upvotes: 1