DEV Community

Discussion on: Let's build a simple Javascript Router

Collapse
 
gprst profile image
Gabriel Proust • Edited

This was very interesting, thank you very much. I'm not sure yet if it fits my use case, but I can tell I found the page content caching very smart, and it's something I haven't seen on other tutorials.

However, I'm unsure if your demo works, and your GitHub link seems dead.

Also, I imagine you already know the function, but you could more idiomatically rewrite pages.filter(p => p.pathname === pathname)[0] by pages.find(p => p.pathname === pathname).

I also wanted to share with you some other way to deal with this pages array. Instead of dealing with its content with getStoredPage() and storeCurrentPage to get an array like this :

const pages = [
    {
        pathname: '/some/path',
        content: '<span>Some content</span>'
    },
    {
        pathname: '/some/other/path',
        content: '<div>Some other content</div>'
    }
]
Enter fullscreen mode Exit fullscreen mode

you could have a global object, whose keys would be the pathnames, and values would be the according pages content. It would be easier to manipulate, in my opinion. It would go like so :

const pages = {
    '/some/path': '<span>Some content</span>',
    '/some/other/path': '<div>Some other content</div>'
};

const pathname = '/a/yet/unvisited/path';
const pageContent = pages[pathname]; // instead of getStoredPage(pathname)
if (pageContent) {
    // do something with the page content...
} else {
    pages[pathname] = pageFromText(pageText); // instead of storeCurrentPage()
    // etc.
}
Enter fullscreen mode Exit fullscreen mode

Both methods (yours and mine) are obviously a matter of taste, I just wanted to share mine.

Thank you for your post !