Passing data from one state to another state in react

const [object, setObject] = useState({
        id: null,
        created_date: "2021-02-18",
        classroom:"",
        name: "",
});

i want to pass the create_date value to anther state

const [notify, setNotify] = useState({
        id: 5,
        created_by: "1",
        notification:"object added",
        received_date:created_date,
});

here, i want that created_date value in received_date

2 thoughts on “Passing data from one state to another state in react”

  1. Is this what you wanted to do the reference

    import { useState } from "react";
    
    export default function App() {
      const [object, setObject] = useState({
        id: null,
        created_date: "2021-02-18",
        classroom: "",
        name: ""
      });
    
      const [notify, setNotify] = useState({
        id: 5,
        created_by: "1",
        notification: "object added",
        received_date: object.created_date
      });
    
      return <div>{notify.received_date}</div>;
    }
    
    Reply
  2. You would have to useEffect for that since object will mutate over time, and notify has to keep up with that.

    const initialObject = {
            id: null,
            created_date: "2021-02-18",
            classroom:"",
            name: "",
    }
    
    const [object, setObject] = useState(initialObject);
    
    const [notify, setNotify] = useState({
            id: 5,
            created_by: "1",
            notification:"object added",
            received_date:initialObject.created_date,
    });
    
    useEffect(()=>{
       setNotify(notify => ({...notify, received_date: object.created_date})
    }, [object])
    
    Reply

Leave a Comment