0

I am new to react and I am trying to build a todo app which basically can execute the CRUD operation. I am able to update and delete as of now. But not sure how to create an object and save it into the array.

When i click on edit or add task button a modal pop up and i am trying to enter the title and description value there.

This is my Index.js file

import React, {Component} from 'react';
import { Button, Modal } from 'reactstrap';
import Modals from './Modals'


const todoItems = [
  {
    id: 1,
    title: "Go to Market",
    description: "Buy ingredients to prepare dinner",
    completed: true
  },
  {
    id: 2,
    title: "Study",
    description: "Read Algebra and History textbook for upcoming test",
    completed: false
  },
  {
    id: 3,
    title: "Sally's books",
    description: "Go to library to rent sally's books",
    completed: true
  },
  {
    id: 4,
    title: "Article",
    description: "Write article on how to use django with react",
    completed: false
  }
];


class Index extends Component {
  state = { 
      modal: false,
      items: todoItems,
      selectedItem: null,
      selectedIndex: -1,
   }

    toggle = (item, index) => {
    if (item) {
     this.setState({ selectedItem: item, selectedIndex: index })
    }
    this.setState({ modal: !this.state.modal });
    };

    handleChange = () => {
      let oldState = this.state.items;
      this.setState({ items: oldState })
    }

    onDelete = (item) => {
      const newData = this.state.items.filter(i => i.title !== item.title)
      this.setState({ items: newData })
    }



  render() { 
    return ( 
      <>
      <h1 className="p-3">TODO APP</h1>
      <div style={{ backgroundColor: "white", padding: "50px", color: "black"}} className="container">
        <div className="row">
        <button className="btn btn-primary" onClick={() =>  this.toggle()}>Add task</button>
        </div>
        <div className="row my-5">
        <Button color="danger mr-5">Incomplete</Button>
        <Button color="success">Complete</Button>
        <Modals index={this.state.selectedIndex} onDelete={this.onDelete}  item={this.state.selectedItem} handleChange={this.handleChange} modal={this.state.modal} toggle={this.toggle} />

        </div>
        <hr/>
        {this.state.items.map((item, index) => {
          return(
            <div key={item.id}>
            <div className="row">
            <p style={{ textAlign: "left" }}>{item.title}</p>
              <Button onClick={() =>  this.toggle(item, index)} className="mr-0 ml-auto" color="info">Edit</Button>
              <Button onClick={() => this.onDelete(item)} className="ml-5" color="warning">Delete</Button>
            </div>
            <hr/>
            
            </div>
            )
          })}
      </div>
      </>
     );
  }
}
 
export default Index;

This is my modal.js file

import React, { useState, useEffect } from 'react';
import { Button, Modal, ModalHeader, ModalBody, ModalFooter } from 'reactstrap';

function Modals(props) {

    const {
        className,
        buttonLabel,
        handleChange,
        item,
        index,
        toggle,
      } = props;
    
    const [title, setTitle] = useState('');
    const [description, setDescription] = useState('');

  useEffect(() => {
      if (item && item.title){
      setTitle(item.title)
      setDescription(item.description)
    }
    }, [item])
  

    const setValues = () => {
      handleChange({ title: title, description: description });
      props.toggle();
      push({

      })
    }


    return (
        <div>
      <Modal isOpen={props.modal} className={className} style={{ color: "black"}}>
        <ModalHeader >Todo Item</ModalHeader>
        <ModalBody>
          <div className="container-fluid">
              <div className="row mb-3">
                  <div className="col-12">
                    <p className="mb-0">Title</p>
                  </div>
                  <div className="col-12">
                      <input onChange={(e) => setTitle(e.target.value)} value={title} className="w-100" type="text" placeholder="Enter title"/>
                  </div>
              </div>
              <div className="row mb-3">
                  <div className="col-12">
                    <p className="mb-0">Description</p>
                  </div>
                  <div className="col-12">
                      <input type="text" onChange={(e) => setDescription(e.target.value)} value={description} className="w-100" placeholder="Enter Description"/>
                  </div>
              </div>
              <div className="row">
                  <div className="col-12">
                    <input type="checkbox"/>
                   <span className="ml-2"> Completed </span>
                  </div>
              </div>
          </div>
        </ModalBody>
        <ModalFooter>
          <Button onClick={() => setValues()}  color="success">Submit</Button>
          <Button onClick={props.toggle} color="secondary">Cancel</Button>
        </ModalFooter>
      </Modal>
    </div>
    )
  }


  export default Modals;

Thanks in advance!!

1 Answer 1

1

One way would be to just create a method in index.js

addItem = (item) =>{
  this.setState({items: [...this.state.items, item]})
}

and then just pass it as a prop to your Modal and call it in setValues,

const setValues = () => {
  handleChange({ title: title, description: description });
  props.toggle();
  props.addItem({ title: title, description: description, //etc})
}
Sign up to request clarification or add additional context in comments.

2 Comments

This works. But could you let me know what are you trying to do with the code inside index.js? If i am not wrong i understand you are trying to copy the state.items using spread operator and assigning it to a variable. But what does the comma item do?
That appends item to the copied array

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.