vamsi
vamsi

Reputation: 231

SetState inside UseEffect causing infinite loop

export const Upload = ({ initialfileList = [] }) => {
  console.log("called...")
  const [files,setFiles] = useState(initialfileList)
  useEffect(() => {
    setFiles(initialfileList)
  }, [initialfileList])
  return(
    .....
   )
}

I will not be sending initialfileList in intial render. so I'm trying to update the state (files) when intialfileList value Changes. But I'm not able to get why code is going into infinite loop.. Can someone help...

EDIT: what I'm trying to achieve is there are two uploads in the form (say upload A and upload B) and checkbox as well. when the user uploads an image (say imgc) in Upload A and hits the checkbox, I wanted img c to be autouploaded in Upload B as well..

Upvotes: 3

Views: 88

Answers (2)

Charles
Charles

Reputation: 199

Ah, I see. How about this?

export const Upload = ({ initialfileList = [] }) => {
   const [files, setFiles] = useState(initialfileList);
   useEffect(() => {
      function isDifferentFiles(originFiles, newFiles) {
         return originFiles.length !== newFiles.length; // or whatever logic here.
      }
      if (isDifferentFiles(files, initialfileList)) {
         setFiles(initialfileList);
      }
   }, [initialfileList]);
   return <div>{files.length}</div>;
};

Btw, you might need to consider move the state to parent.

Upvotes: 2

A McBride
A McBride

Reputation: 405

It sounds like you need to lift your state up - rather than storing fileLists locally, store a single fileList in the parent component, pass that down to both Upload A and Upload B, and also pass a setFileList function (which updates the state in the parent component).

i.e.:

// parent component
const Parent = () => {
    const [fileList, setFileList] =  useState([])
    return (
        <Upload fileList={fileList} setFileList={setFileList} />
        <Upload fileList={fileList} setFileList={setFileList} />
    )
}
const Upload = ({fileList, setFileList}) => {
    return (
        <UploadComponent files={fileList} onUpload={setFileList} />
    )
}

This way, either upload component being updated will update both.

Upvotes: 0

Related Questions