0

I am parent component that got table, when user click on row, it needs to pass the object to Child component via history.push which is all working fine. I have define an object of same type in child component and trying to assign value which is coming via location. I can clearly see value in object but child component states 'Undefined' not sure what I am missing from puzzle?

Object Definition

 export interface ISearchCriteriaForm{
   startTime: string,
   endTime: string,
   liveTime?: string,
   schedAction_Active: string,
   siteId?: number,
   scheduleId?: number
 }

Parent Component

 const selectedRow = (row: any) => { 

  eziStatusSearchCriteria.siteId = row.siteId;
  history.push({
    pathname: `${url}/${row.siteId}`,
    state: {searchCriteria: eziStatusSearchCriteria}
  });
 };

Child Component

const MyChildComponent = () =>{
   const[eziSearchCriteria, setEziSearchCriteria] = useState<IEziStatusSearchCriteriaForm>();

  useEffect(() =>{
    setSearchCriteria();
  },[]);

   const setSearchCriteria =() =>{
  
    const s1: IEziStatusSearchCriteriaForm = location.state.searchCriteria;  // in debugger, I can see data in s1
     setEziSearchCriteria(s1);
     console.log("data ",eziSearchCriteria);  // this console undefined???? need help here        
    }
K.Z
  • 5,201
  • 25
  • 104
  • 240
  • can you try achieve your state via useEffect, I think the state don't set immediately so test this-> useEffect(() => { console.log("data ",eziSearchCriteria); }, [eziSearchCriteria]); – barzin.A Jan 03 '21 at 09:26
  • React state updates are asynchronously processed and available on the *next render*, so console logging state *right after* an update is enqueued will only ever log the current state from the current render cycle. In your case the initial state which is undefined. – Drew Reese Jan 03 '21 at 09:38

1 Answers1

1

Try this now,

const MyChildComponent = () =>{
   const[eziSearchCriteria, setEziSearchCriteria] = useState<IEziStatusSearchCriteriaForm>();

  useEffect(() =>{
    setSearchCriteria();
  },[eziSearchCriteria]); // always give dependeny of the data that is chnaging, so that component re-render when this changes

   const setSearchCriteria =() =>{
  
    const s1: IEziStatusSearchCriteriaForm = location.state.searchCriteria;  // in debugger, I can see data in s1
     setEziSearchCriteria(s1);
     console.log("data ",eziSearchCriteria);  // this console undefined???? need help here        
    }
Muhammad Jaan
  • 291
  • 3
  • 10