DEV Community

Tony Lobbin
Tony Lobbin

Posted on

πŸ˜“ I have some issue in React

I couldn't understand this issue.
please explain me about this.
I attach source code and error image.
https://github.com/elitesuper/my_issue/blob/main/CollectionUpload.tsx
Image description

Top comments (5)

Collapse
 
tiguchi profile image
Thomas Werner • Edited

The React error message tells you exactly what the problem is. The CollectionUpload component state is being updated while rendering the component UploadProgress.

So let's break down what's happening here.

Function Component Render Cycle

In a React function component the function body is basically the render method of the component. Whatever happens inside the function component body, happens during that component's render cycle.

function MyComponent() {
    // Any code here runs during the render cycle of MyComponent

    return <div>Some result</div>;
}
Enter fullscreen mode Exit fullscreen mode

You need to be careful with updating state from there, especially when it's the state of another component.

Cause Of The Error Message

Your UploadProgress component has the following lines of code that probably cause the problem:

    if (progressData && progressData.completed > progress) {
      setProgess(() => progressData.completed);
      setupload(true);
    }
Enter fullscreen mode Exit fullscreen mode

It's the setupload(true) call which updates the state of the CollectionUpload component while UploadProgress is being rendered.

Effect Hooks Solve The Problem

Effect hooks can be used for deferring the execution of code after the component was rendered, so basically after the function component was called and returned its render result. You can look at them as callback functions that are queued for execution after component rendering took place.

function MyComponent() {
    // Any code here runs during the render cycle of MyComponent

    useEffect(() => {
        // This code here runs after MyComponent was rendered, and when
        // the values in the dependency array have changed or when MyComponent
        // was rendered for the first time
    }, [someDependency])

    return <div>Some result</div>;
}
Enter fullscreen mode Exit fullscreen mode

You could wrap that problematic if statement that calls setupload(true) in another useEffect to solve the problem.

Collapse
 
elitesuper profile image
Tony Lobbin

πŸ‘ Thank you very much, Your method is very useful!

Collapse
 
elitesuper profile image
Tony Lobbin • Edited

😁 Thanks for your message!

Let me check.
kind regards!

Collapse
 
hoangtd profile image
hoangtd21

Split the UploadProgress component into another file, then import it and use it in CollectionUpload

Collapse
 
elitesuper profile image
Tony Lobbin • Edited

πŸ˜ƒ Thanks for your message!!!
But This Warning still exist.
please check this.
github.com/elitesuper/my_issue