Serhii
Serhii
PD🧩 Plasmo Developers
Created by Serhii on 3/19/2024 in #🔰newbie
React route is rendered twice when I use useStorage hook
Hey everyone, I'm having an issue with my extension. I'm using Plasmo and react-router together. When I render a route in which I need to call useStorage my component is rendered twice, I can't quite understand why this is happening. Here is my route:
{
path: '/edit',
element: <EditNote />,
},
{
path: '/edit',
element: <EditNote />,
},
When I click this button:
<Button
action={() => {
console.log('edit clicked'); // Called once
navigate(`/edit`);
}}
/>
<Button
action={() => {
console.log('edit clicked'); // Called once
navigate(`/edit`);
}}
/>
Here is my route code:
import { useNavigate } from 'react-router-dom';

import { Storage } from '@plasmohq/storage';
import { useStorage } from '@plasmohq/storage/hook';

import { StorageKey } from '~constants';
import type { NoteOutput } from '~schemas/schema';

type Notes = { [key: number]: NoteOutput };

export function EditNote() {
// If I remove this const everything is rendered once.
const [notes] = useStorage<Notes>({
key: StorageKey.NOTES,
instance: new Storage({
area: 'local',
allCopied: true,
}),
});
const navigate = useNavigate();

// Called twice
console.log('edit');

// Called twice, first with [] and then with multiple notes [{...}, {...}, ...]
console.log(notes);

return (
<div>
<button onClick={() => navigate(`/`)}>back</button>
</div>
);
}
import { useNavigate } from 'react-router-dom';

import { Storage } from '@plasmohq/storage';
import { useStorage } from '@plasmohq/storage/hook';

import { StorageKey } from '~constants';
import type { NoteOutput } from '~schemas/schema';

type Notes = { [key: number]: NoteOutput };

export function EditNote() {
// If I remove this const everything is rendered once.
const [notes] = useStorage<Notes>({
key: StorageKey.NOTES,
instance: new Storage({
area: 'local',
allCopied: true,
}),
});
const navigate = useNavigate();

// Called twice
console.log('edit');

// Called twice, first with [] and then with multiple notes [{...}, {...}, ...]
console.log(notes);

return (
<div>
<button onClick={() => navigate(`/`)}>back</button>
</div>
);
}
As it returns first empty array and then with data, this gives me a hint that some async stuff is happening behind the scenes, but the type definition of useStorage says nothing about async in read value. Has anyone faced with similar issue and solved it? P.S. StrictMode is disabled.
2 replies