Home > Software engineering >  Why doesn't the table appear?
Why doesn't the table appear?

Time:09-26

components/App.js

import React from 'react';
import { connect } from 'react-redux'
import { add_task } from '../actions/index';

class App extends React.Component {
  state = {
    text: '',
    time: ''
  }
  render_tasks = () => {
    const { tasks } = this.props
    return (
      <table>
        <tbody>
          {tasks.map(task => {
              return (
                <tr key={task.id}>
                  <td>{task.text}</td>
                  <td>{task.time}</td>
                </tr>
              )
            })
          }
        </tbody>
      </table>
    )
  }
  render() {
    console.log('App props', this.props)

    return (
      <div className="App">

        <input type='text' 
          onChange={(e) => this.setState({
            text: e.target.value
          })} />
          
        <input type='time' 
        onChange={(e) => this.setState({
          time: e.target.value
        })} />

        <button 
          onClick={() => this.props.add_task(
              this.state.text, this.state.time)}>
            Add
        </button>
          
        {this.render_tasks()}
          
      </div>
    );
  }
}

function mapStateToProps(state) {
  return {
      tasks: state
  }
}

function mapDispatchToProps(dispatch) {
  return {
      add_task : () => dispatch(add_task())
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(App);

actions/index.js

import { ADD_TASK } from './../types';

export const add_task = (text, time) => {
    const action = {
        type: ADD_TASK,
        text,
        time
    }
    console.log('Add action', action)
    return action
}

reducers/index.js

import { ADD_TASK } from './../types';

const tasks = (state=[], action) => {
    let tasks = [];

    if (action.type === ADD_TASK) {
        tasks = [...state, {
            text: action.text,
            time: action.time,
            id: Math.random()
        }]
        console.log('Data from reducer', tasks)
        return tasks
    } else {
        return state
    }
}

export default tasks;

When I click the button I expect to get a table with the information I entered in the input fields, but nothing appears, I tried replacing the table part in render_tasks function in App.js with an unordered list and the map returns a list item including 2 spans one for the text and the other for the time but all I got is the dot of the list item!

CodePudding user response:

In

add_task : () => dispatch(add_task())

You don't pass any arguments to add_task().

You can explicitly define the arguments:

add_task : (text, time) => dispatch(add_task(text, time))
  • Related