SharePoint / sp-dev-docs

SharePoint & Viva Connections Developer Documentation
https://docs.microsoft.com/en-us/sharepoint/dev/
Creative Commons Attribution 4.0 International
1.24k stars 994 forks source link

Web part 'componentDidMount' triggered twice when editing page #9792

Open JoelBool opened 1 month ago

JoelBool commented 1 month ago

Target SharePoint environment

SharePoint Online

What SharePoint development model, framework, SDK or API is this about?

💥 SharePoint Framework

Developer environment

Windows

What browser(s) / client(s) have you tested

Additional environment details

Describe the bug / error

The base component in a a web part will when moving from 'view mode' to 'edit mode' mount twice like this:

  1. Clicking the page 'Edit' control
  2. Component dismounts
  3. Component mounts
  4. Component dismounts
  5. Component mounts

This might be by design (I haven't found any information about it when searching) but could otherwise be a bug. The componentDidMount (or useEffect with no dependencies) are in many cases used to run requests/fetching data necessary for the initialization of a component. When the component is mounted twice such requests that are indended as a one of fetch will be made twice

Steps to reproduce

  1. I created a very simple web part with some minimal console logging to illustrate the issue. Scaffolded through yo @microsoft/sharepoint. Available here: https://github.com/JoelBool/DoubleMountingWebpart
  2. Package the web part and deploy it to a app catalog (npm run package)
  3. Edit a page
  4. Add the webpart to the page (it has the name re-mounting-re-rendering)
  5. Publish the page
  6. Open the developer tools of the browser to see the console.logs
  7. Clear the logs that are in the console (so it's easier to spot the coming ones)
  8. Edit the page
  9. Note that 'ComponentDidMount' is logged twice in the console

The issue does not occur in view mode. Nor when adding a web part when already in edit mode.

Expected behavior

Expecting componendDidMount (or useEffect with no dependencies) to run once when editing a page.

JoelBool commented 1 month ago

As a side note I noticed that the component mounts 4 times when creating a page with a template where the web part is added

  1. Create a page
  2. Add the web part
  3. Save the page as a template
  4. Open the create a page form again
  5. Select your new template and wait for the preview to fully load
  6. Open developer tools and clear the logs (the web part has already been mounted when previewing the template)
  7. Click create
  8. Notice that 'ComponentDidMount' is logged four times in the console