0

This is my parent component js file...

import React, { useContext, useState } from "react";
import TaskListContextProvider from "./TaskListContext";
import TaskList from "./TaskList";
import TaskForm from "./TaskForm";

const AddMenu = () => {
  const [menu, setMenu] = useState({
    menuName: "",
    tag: "",
    price: "",
    menuItem: ""
  });


  const addMenu = (e) => {
    const { name, value } = e.target;
    setMenu((preValue) => {
      return {
        ...preValue,
        [name]: value,
      };
    });
    
  };

   //function to recieve data from child component
    const addList=(data)=> {
    setMenu([...data,{menuItem:data}]);
   };

  const onSubmit = (e) => {
    e.preventDefault();
    console.log(menu);
  };

  return (
        <div className="form-row">
          <div className="form-group">
            <input
              type="text"
              name="menuName"
              onChange={addMenu}
              value={menu.menuName}
            />
          </div>
          <div className="form-group">
            <input
              type="text"
              name="tag"
              onChange={addMenu}
              value={menu.tag}
            />
          </div>
          <div className="form-group">
            <div className="main">
              <TaskListContextProvider addList={addList}>
                <TaskForm />
                <TaskList />
              </TaskListContextProvider>
            </div>
          </div>
          <div>
            <input
              type="number"
              name="price"
              onChange={addMenu}
              value={menu.price}
            />
          </div>
        </div>
        <button
          type="submit"
          onClick={onSubmit}
        >
          Save
        </button>
  );
};

export default AddMenu;

This is my child component js file...

import uuid from 'uuid'

export const TaskListContext = createContext()

const TaskListContextProvider = props => {
  const initialState = JSON.parse(localStorage.getItem('tasks')) || []
  
  const [editItem, setEditItem] = useState(null)
  const [tasks, setTasks] = useState(initialState)
  
// call-back function...
//   const sendData=()=>{
//     props.addList(tasks);
//   }
//   sendData();

  useEffect(() => {
    localStorage.setItem('tasks', JSON.stringify(tasks))
    console.log(tasks);
    props.addList(tasks);
  }, [tasks])

    
  // Add tasks
  const addTask = title => {
    setTasks([...tasks, { title, id: uuid() }]) 
  }
  
  // Remove tasks
  const removeTask = id => {
    setTasks(tasks.filter(task => task.id !== id))
  }
  
  // Clear tasks
  const clearList = () => {
    setTasks([])
  }
  
  // Find task
  const findItem = id => {
    const item = tasks.find(task => task.id === id)
    setEditItem(item)
  }

  // Edit task
  const editTask = (title, id) => {
    const newTasks = tasks.map(task => (task.id === id ? { title, id } : task))
    
    console.log(newTasks)

    setTasks(newTasks)
    setEditItem(null)
  }

  return (
    <TaskListContext.Provider
      value={{
        tasks,
        addTask,
        removeTask,
        clearList,
        findItem,
        editTask,
        editItem
      }}
    >
      {props.children}
    </TaskListContext.Provider>
  )
}

export default TaskListContextProvider 

My question : How to send child component "tasks" variable data which contains array of objects to parent component and store them into object "menuItem" , so whenever i click on the save button it should display menu on the console??

1 Answers1

0

you can do this ...

  useEffect(() => {
    localStorage.setItem('tasks', JSON.stringify(tasks))
    props.addList(tasks);
  }, [tasks])

here right after setting the tasks into local storage you can send the data to parent.

Mohammad Faisal
  • 2,265
  • 1
  • 10
  • 16
  • Please don't post only code as answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes. – Mark Rotteveel Sep 20 '20 at 11:53
  • I updated my answer with an explanation . if it helps an upvote would be nice :P – Mohammad Faisal Sep 20 '20 at 12:17
  • It works , but if i press the save button again getting only tasks data and not showing other parent component objects : menuName: "", tag: "", price: "", I also updated my above code... – Vrushabh Kulye Sep 20 '20 at 12:30
  • const addList=(data)=> { setMenu([...data,{menuItem:data}]); }; what is this line doing ? – Mohammad Faisal Sep 20 '20 at 13:12
  • it is taking all the previous data and adding tasks variable into menuItem object. Can you correct that function ? I have a que how to pass only "tasks" variable data (which contains array of object ) into menuItem and keeping other object as it is ?? – Vrushabh Kulye Sep 20 '20 at 13:59
  • as far as i understand it should be setMenu({...menu , menuItem:data}); – Mohammad Faisal Sep 20 '20 at 14:02
  • you want your menu to be an object right ? or an array ? – Mohammad Faisal Sep 20 '20 at 14:05
  • and yeah i upvoted your answer thanks ..one more doubt i am getting warning in child component in useEffect that : React Hook useEffect has a missing dependency: 'props'. – Vrushabh Kulye Sep 20 '20 at 14:17
  • Dont worry about that . If you want to avoid that add the props into your useEffect dependency array – Mohammad Faisal Sep 20 '20 at 14:19