skip to Main Content

I have function in parent component

 

const getFilename=  (filedata)=>  
{
    console.log(filedata);      
}

And pass call a child component from parent

<FileUpload getFieDetails={getFilename} />

Childcomponent function:


const [files, setFiles] = useState([])

const uploadHandler = (event) => {     
    const file = event.target.files[0];      
    console.log(file);     
    if(!file) return;      
      
    file.isUploading = true;
    setFiles((prevState) => [...prevState, file]) 
    props.getFieDetails(files);
)
}

when i console files from child component all the value is listing.But in parent component one data is always missing.Thanks in advance

3

Answers


  1. Since useState is a async function, the last data you are adding in the setFiles won’t be updated in the files when props.getFieDetails(files) is called.

    I would suggest, you call the it inside a useEffect in the child component, so that it will be executed every time file changes in the uploadHandler function

    useEffect(()=>{
     props.getFieDetails(files)
    },[files])
    
    Login or Signup to reply.
  2. The problem is that setFiles is asynchronous. When you call setFiles(...), React re-renders your component and the files state will be stale until the next render. Therefore, calling props.getFileDetails(files) immediately after will pass the previous files state.

    Option 1:

    Create a new array and call setFiles and props.getFilename with the new value.

    const uploadHandler = () => {
      ...
      const newFiles = [...files, file];
      setFiles(newFiles);
      props.getFileDetails(newFiles);
    };
    

    Option 2:

    Call props.getFileDetails in a useEffect.

    const uploadHandler = () => {
      ...
      const newFiles = [...files, file];
      setFiles(newFiles);
      props.getFileDetails(newFiles);
    };
    
    useEffect(() => {
      props.getFileDetails(files);
    }, [props.getFileDetails, files]);
    
    Login or Signup to reply.
  3. You can call getFieDetails inside setFiles callback

    like this:

    const uploadHandler = event => {
      const file = event.target.files[0];
      console.log(file);
      if (!file) return;
      file.isUploading = true;
    
      setFiles(prevState => {
        let filesArr = [...prevState, file];
        props.getFieDetails(filesArr)
        return filesArr
      });
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search