How to get Javascript on an innerHTML working without jQuery?

I’m having problems getting the JS code linked in the innerHTML of my main HTML page working. I have a main HTML file that has these divs:

<div class="content">
    <div class="intro">
        <img src="nightTree.jpg">
        <div class="inner-intro">
            <h1>EDUPLANNER</h1>
            <p>a student scheduling webapp</p>
        </div>
    </div>
</div>
<div class="scripts">
    <script src="home.js"></script>
</div>

and this is the JS code (home.js) for the main HTML file to insert the innerHTML:

document.addEventListener("DOMContentLoaded", () => {
    const content = document.querySelector(".content"),
    sidebarLinks = document.querySelectorAll(".sidebar a");
 
    sidebarLinks.forEach(link => {
        link.addEventListener("click", event => {
            if (link.classList.contains("do-nothing")) {
                event.preventDefault();
                return;
            }

            event.preventDefault();
            var href = link.getAttribute("href");

            fetch("http://127.0.0.1:5500/" + href)
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`HTTP error! Status: ${response.status}`);
                    }
                    return response.text();
                })
                .then(data => {
                    var parser = new DOMParser();
                    var parsedDocument = parser.parseFromString(data, "text/html");
                    
                    if (parsedDocument.querySelector(".day")) {
                        var script = document.createElement("script");
                        script.src = "calendar.js";
                        document.querySelector(".scripts").appendChild(script);
                    }

                    content.innerHTML = parsedDocument.body.innerHTML;
                })
                .catch(error => {
                    console.error("Error fetching content:", error);
                });
        });
    });
});

This is the CSS for “content” class.

.content {
    position: relative;
    background-color: rgb(33, 33, 33);
    height: 100vh;
    width: calc(100% - 80px);
    left: 80px;
    transition: all 0.5s ease;
    padding: 1rem;
}

This is the innerHTML of what I’m trying to get into the main file:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Test Page</title>
</head>
<body>
    <div class="day"></div>
    <script src="calendar.js"></script>
</body>
</html>

and the JS code for the innerHTML:

console.log("Test 1");

document.addEventListener('DOMContentLoaded', () => {
    console.log('DOMContentLoaded event fired');

    let dayDiv = document.querySelector(".day");

    // Simplified for testing
    var newDiv = document.createElement("div");
    newDiv.textContent = "Test";
    dayDiv.appendChild(newDiv);

    console.log("For loop executed");
});

console.log("Test 2");

When the innerHTML is loaded on the main page, only “Test 1” and “Test 2” were shown on the console. Everything in document.addEventListener() doesn’t load. I’ve tried changing the fetch codes, where the JS files are parsed and tried window.onload but nothing worked.

P.S. I’m quite new to HTML, CSS and JS so some of my code may be wrong.

Obfuscate in-line Tailwind CSS classNames in NextJS

I have a NextJS 13 application using Tailwind CSS. I have code like the following

<div className="flex items-center justify-center mt-16 mx-auto">
          ....
</div>

When I use developer tools, my entire application skeleton is exposed, making it easy for anyone to download the HTML and duplicate it.

How can I obfuscate my classNames so that they are hashed? I’m looking for something like this:

enter image description here

All of the existing solutions cover cases where the CSS is defined on another file and imported into the Components for use.

How to fix TypeError: res.status is not a function at GET [closed]

I’m writing code in next.js 14 and I’m having a problem where I can’t pass http status using res.status(200).

This is my code:

import { NextApiRequest, NextApiResponse } from "next";
import prisma from "@/app/services/prisma";

export const dynamic = "force-dynamic";
export async function GET(req: NextApiRequest, res: NextApiResponse) {
  try {
    const schoolsData = await prisma.dados.findMany();
    res.status(200).json(schoolsData);
  } catch (error: unknown) {
    if (error instanceof Error) {
      res.status(500).json({ error: error.message });
    } else {
      res.status(500).json({ error: "Ocorreu um erro com o servidor." });
    }
  }
}

This code is within the path: src/app/api/getData/route.ts

I hope you identify the error and explain it to me so that I don’t get stuck again.

Regular Expressions Bug with Javascript/React

I have 3 regular expressions here. USERNAME_REGEX & EMAIL_REGEX work independently without any errors. However when I use IDENTITY_REGEX it gives me an invalid character class error:

REGEX

export const USERNAME_REGEX = "[A-Za-z0-9]{3,16}"
export const EMAIL_REGEX = "[w.-]+@([w-]+.)+[w-]{2,4}"
export const IDENTITY_REGEX = "[A-Za-z0-9]{3,16}|[w.-]+@([w-]+.)+[w-]{2,4}"

Usage Component

  const inputs = [
    {
      id: "identity",
      name: "identity",
      type: "text",
      errorMessage:
        "Username should be 3-16 characters, no special characters allowed",
      label: "Email Address / Username",
      pattern: IDENTITY_REGEX,
      required: true
    },

.....

<FormInput
  key={input.id}
  {...input}
  onChange={onChange}
/>

ERROR

Pattern attribute value [A-Za-z0-9]{3,16}|[w.-]+@([w-]+.)+[w-]{2,4} is not a valid regular expression: Uncaught SyntaxError: Invalid regular expression: /[A-Za-z0-9]{3,16}|[w.-]+@([w-]+.)+[w-]{2,4}/v: Invalid character in character class

I appreciate your time in advance!

Tried new RegExp() but to no avail

DOM objects does not work with className and checked included

Have found something strange with DOM and handling as an object.
Tried having className and checked as part of the object. This has not worked, can’t find a reason for it or an explanation.

Does anyone have an idea what it is I’ve stumbled upon here? and where can I read/understand more?

function farge_knapp_ikke_fungernde(ID) {
    var checkbox = document.getElementById(ID).checked;
    var button = document.getElementById(ID + '_button').className;

    if (checkbox == false) {
      
        checkbox = true;
        button = button.replace(" w3-white"," w3-light-green" );
    } else {
      
        checkbox = false;
        button = button.replace(" w3-light-green"," w3-white" );
    }
   
}

This edition works. but has duplicate code. little in this example, but I have larger examples that I wish to clean up.

function farge_knapp(ID) {
    var checkbox = document.getElementById(ID);
    var button = document.getElementById(ID + '_button');

    if (checkbox.checked == false) {
        
        checkbox.checked = true;
        button.className = button.className.replace(" w3-white"," w3-light-green" );
    } else {

        checkbox.checked = false;
        button.className = button.className.replace(" w3-light-green"," w3-white" );
    }
    
}

Have found something strange with DOM and handling as an object.
Tried having className and checked as part of the object. This has not worked, can’t find a reason for it or an explanation.

Does anyone have an idea what it is I’ve stumbled upon here? and where can I read/understand more?

function farge_knapp_ikke_fungernde(ID) {
    var checkbox = document.getElementById(ID).checked;
    var button = document.getElementById(ID + '_button').className;

    if (checkbox == false) {
      
        checkbox = true;
        button = button.replace(" w3-white"," w3-light-green" );
    } else {
      
        checkbox = false;
        button = button.replace(" w3-light-green"," w3-white" );
    }
   
}

This edition works. but has duplicate code. little in this example, but I have larger examples that I wish to clean up.

function farge_knapp(ID) {
    var checkbox = document.getElementById(ID);
    var button = document.getElementById(ID + '_button');

    if (checkbox.checked == false) {
        
        checkbox.checked = true;
        button.className = button.className.replace(" w3-white"," w3-light-green" );
    } else {

        checkbox.checked = false;
        button.className = button.className.replace(" w3-light-green"," w3-white" );
    }
    
}

Not sure what to write as a question on this matter. Any better suggestions?

how to inject a dependency in a subclass with nestjs

My service provider has a subclass and this subclass has a dependency.

I am having a hard time trying to make this work.

here is the controller where I inject the service class:

@Controller('/chat')
export class ChatController {
    constructor(
        private sendMessageAuthorizationService: SendMessageAuthorizationService
    ) {
    }

    @Get('/authorization')
    isAuthorized() {
        return JSON.stringify("hello world");
    }
}

here is the service class:

@Injectable()
export class SendMessageAuthorizationService {
    private getUserChatRule: GetUserChatRule;

    constructor(
        userChatGatway: UserChatGateway
        ) {
        this.getUserChatRule = new GetUserChatRule(userChatGatway);
    }

    execute() {
        return "hello world";
    }
}

here is the subclass that has a dependency:

export default class GetUserChatRule {
    constructor(
        private readonly userChatGateay: UserChatGateway
    ) {
    }

    apply() {
        return "hello world";
    }
}

here is the class that is being inject into the subclass GetUserChatRule

@Injectable()
export default class UserChatAdapter implements UserChatGateway {
    getUserChat() {
        return "hello world";
    }
}

finally here is the module:

@Module({
    imports: [],
    controllers: [ChatController],
    providers: [SendMessageAuthorizationService, UserChatAdapter]
})
export class ChatModule {}

for reference, this is the error I get:

Error: Nest can't resolve dependencies of the SendMessageAuthorizationService (?). 
Please make sure that the argument Object at index [0] is available in the ChatModule context.

Why callbacks work in Promises but await don’t?

Why can I have async code like getting db connection with callback, that is working perfectly fine, but I can’t await same code in Promises.

For example

return new Promise((resolve, reject) => {
     mySql.getConnection((error, connection) => {
         /* code goes here */
     })
}

Code above works like a charm. But if I try to do something like:

return new Promise(async (resolve, reject) => {
     try {
         const connection = await mySql.getConnection();
     } catch (error) {
         throw error;
     }
}

Code above is considered anti-pattern because async (resolve, reject) will return new Promise, and I will end up with Promise inside Promise.

I tried calling self-invoking function and decorate that with async, which does not work because I am not awaiting that function.
Source: https://simonjcarr.medium.com/using-async-inside-a-javascript-promise-f32957617d78

How would I sort these HTML items without recreating the DOM upon each sort? I’m working with the View Transition API

Hey ya’ll I have a question that involves the View Transition API. Sorry for the length, just trying to be thorough…

I’m working on a web app that renders HTML elements from an array of objects. It also has a number of filter buttons and sorting buttons. The filter buttons look at the current dom nodes and for whichever one matches the filter, the ‘hidden’ attribute gets added to that element. However, the sorting buttons sort the original array, empty the parent container, recreate the HTML elements, add them to a document fragment, then add that fragment to the parent container.

Does that sound right or is there another way to sort HTML elements without getting all…DOM ‘rewritey? I’ve looked at the CSS rule “order” for flex and grid elements, and while that changes the position visually, it screws with accessibility by not actually changing the DOM node order.

I just realized that I do have access to JQuery, so I may give that a go, but I’d rather keep it vanilla JS.

It’s not a big issue, but I’m playing with the View Transition API and the results for when I rebuild the entire DOM are a little wonky versus when I simply add the hidden attribute. This is the video I’m working from btw.

https://www.youtube.com/watch?v=jZiZs8cZAKU

You can see towards the 27:45 mark that to get the collapsible feature, he programmatically adds View Transition names for each element in the list. I’m doing something like that but the collapsible feature doesn’t come through that well if I’m rebuilding all of the elements again.

When I pull data with the API in Redux, the same data is pulled over and over again

I’m just learning React.js and redux concepts. I wanted to make a movie application with API. I was able to pull the data the way I wanted. However, the “movieContainer” in my “MovieItem.jsx” file appears on the screen twice, and every time I check my codes, this number increases. I couldn’t find where I made a mistake.

—— MOVİELİSTSLİCE.JSX—–


export const getMovie = createAsyncThunk("movieList/getMovie", async () => {
  
  const apiKey = '*********************';
  const apiUrl = `https://api.themoviedb.org/3/discover/movie?api_key=${apiKey}`;
  
  try {
    
    let response = await fetch(apiUrl);
    let json = await response.json();
    console.log(json);
    return json;
    
  } catch (error) {
    console.error('Error:', error);
    throw error;
  }
});

const movieListSlice = createSlice({
  name: "movieList",
  initialState: {
    movies: [], // Başlangıçta boş bir dizi
    status: null,
    error: null, // Yeni eklenen hata alanı
  },
  reducers: {}, // Eğer gelecekte reducer eklemek isterse bu alan kullanılabilir
  extraReducers: (builder) => {
    builder
      .addCase(getMovie.pending, (state) => {
        state.status = "Fetching movies. Please wait a moment...";
      })
      .addCase(getMovie.fulfilled, (state, action) => {
        let updatedMovies = state.movies.concat(action.payload);
        state.movies = updatedMovies;
        state.status = null;
      })
      .addCase(getMovie.rejected, (state, action) => {
        state.status = "Failed to fetch data...";
        state.error = action.error.message; // Hata mesajını sakla
      });
  },
});


 ------ `MOVİELİST.JSX ------`

const MovieList = () => {
  const dispatch = useDispatch();
  const { movies, status } = useSelector((state) => state.movieList);
  console.log({ movies, status });
  useEffect(() => {
    if (movies.length === 0) {
      dispatch(getMovie());
    }
  }, [dispatch, movies]);

  return (
    <div>
      <ul>
        {movies.map((movie) => {
          // return ;
          return <MovieItem {...movie} key={movie.id}/>;
        })}
        
      </ul>
    </div>
  );
};

  -------`MOVIEITEM.JSX`------


const MovieItem = (props) => {
  return (
    <div className="movieContainer">
      {props.results.slice(0, 20).map((movie, index) => (
        <div key={index} className='movieCard'>
          <h3 className='title'>{movie.title}</h3>
          <img src={`https://image.tmdb.org/t/p/w500/${movie.poster_path}`} alt={movie.original_title}              width={400} height={200}/>

          <ul>
            <li><strong>Açıklama:</strong> {movie.overview}</li>
            <li><strong>Yayın Tarihi:</strong> {movie.release_date}</li> 
            <li><strong>Popülerlik:</strong> {movie.popularity}</li>  
          </ul>
        </div>
      ))}
    </div>
  );
};


The codes I use in my project are as follows.
I’m waiting for your help 🙂

Not being able to import file type “train-images.idx3-ubyte” to be used in the front-end

What methods could you use to import uncommon external files like the idx3/1-ubyte into the client’s end website folder within vanilla javascript?

  1. Used the fileReader() function to grasp file’s info, but what I got is the following: Failed to execute 'readAsDataURL' on 'FileReader': parameter 1 is not of type 'Blob'..

  2. Also tried to use XML Request to the file, but still cannot fetch it because it wasn’t really present in the client’s folder.

  3. Through some Stack Overflow searching, I also tried the file input to receive a default value <input type="file" value="./train-images.idx3-ubyte">. Somehow, people said it wasn’t really possible to be given a default value on a file type for “security reasons”.

Not getting the desired output after MongoDb query

Requirement is to fetch user details which matches the input search(name or email) by the logged in user.

Currently I am able to fetch the unique users related to the logged in user but not able to query by using the user inputs.

This is my client-side api call:

const handleSearch = async () => {
    if (!search) {
        toast({
            title: 'Please enter name or email',
            status: 'error',
            duration: 5000,
            isClosable: true,
            position: 'top',
        });
        return;
    }
    try {
        setloading(true);
        const config = {
            headers: { Authorization: `Bearer ${user.token}` },
        };
        console.log(typeof search);
        const { data } = await axios.get(`/api/chat?search=${search}`, config);

        console.log(data);

        setsearchResults(data);

        setloading(false);
    } catch (error) {
        toast({
            title: 'Error occurred',
            description: 'Failed to load the search results',
            status: 'error',
            duration: 5000,
            isClosable: true,
            position: 'top',
        });
        setloading(false);
    }
};

Here’s my api handler:

const fetchChats = expressAsyncHandler(async (req, res) => {
console.log('inside fetch chats');
console.log(typeof req.query.search);
const keyword = req.query.search
    ? {
            $or: [
                { name: { $regex: req.query.search, $options: 'i' } },
                { email: { $regex: req.query.search, $options: 'i' } },
            ],
      }
    : {};
console.log('keyword : ', { ...keyword });
try {
    const currentUserChats = await Chat.find({
        users: req.user._id,
        // ...keyword,
    });
    console.log(currentUserChats, "current user's chats");
    const participantIds = currentUserChats.reduce((ids, chat) => {
        chat.users.forEach((userId) => {
            if (
                userId.toString() !== req.user._id.toString() &&
                !ids.includes(userId.toString())
            ) {
                ids.push(userId.toString());
            }
        });
        return ids;
    }, []);
    console.log(participantIds, 'retrieved ids');
    const users = await User.find({ _id: { $in: participantIds } }).select(
        '-password'
    );
    res.status(200).send(users);
} catch (error) {
    res.status(400);
    throw new Error(error.message);
}

});

FYI: api is being called correctly, “typeof req.search.query” is string, if I remove “…keyword” as in the above image, it works for fetching users without the query entered by user.

Now I want to filter the users on the basis of name or email entered by user.

How can I wait for a websocket message in python

I’m trying to replicate this js test in python

  • test.js
it.only('should send and receive PSS message', async function () {
    this.timeout(PSS_TIMEOUT)

    return new Promise<void>((resolve, reject) => {
      ;(async () => {
        const topic = 'send-receive-pss-message'
        const message = 'hello'

        const ws = pss.subscribe(BEE_URL, topic)
        ws.onmessage = ev => {
          const receivedMessage = Buffer.from(ev.data as string).toString()

          // ignore empty messages
          if (receivedMessage.length === 0) {
            return
          }
          ws.terminate()
          expect(receivedMessage).to.eql(message)
          resolve()
        }

        const addresses = await connectivity.getNodeAddresses(BEE_DEBUG_KY)
        const target = addresses.overlay
        await pss.send(BEE_PEER_KY, topic, makeTestTarget(target), message, getPostageBatch(BEE_DEBUG_PEER_URL))
      })().catch(reject)
    })
  })
  • test.py
@pytest.mark.timeout(PSS_TIMEOUT)
@pytest.mark.asyncio
async def test_send_receive_pss_message(bee_url, bee_debug_ky_options, bee_peer_ky_options, get_peer_debug_postage):
    topic = "send-receive-pss-message"
    message = "hello"

    ws = await subscribe(bee_url, topic)

    addresses = get_node_addresses(bee_debug_ky_options)
    target = addresses.overlay
    send(bee_peer_ky_options, topic, make_test_target(target), message, get_peer_debug_postage)

    received_message = await ws.recv()
    assert received_message == message
    ws.close()
  • subscribe
async def subscribe(url: str, topic: str) -> websockets.WebSocketClientProtocol:
    """
    Subscribes to messages on the given topic.

    Args:
        url (str): Bee node URL.
        topic (str): Topic name.

    Returns:
        websockets.WebSocketClientProtocol: WebSocket connection to the subscription endpoint.
    """
    ws_url = url.replace("http", "ws")
    ws_url = f"{ws_url}/{PSS_ENDPOINT}/subscribe/{topic}"
    return await websockets.connect(ws_url)
  • So how can I keep the connection open until I receive the message? The js test took a couple of mins to run. But the python test is stuck for 30 mins if I try to use a while loop. What am I doing wrong ? please I need help.

Google Extension Doesn’t Append the HTML on Every Refresh

My Manifest.json:

{
  "manifest_version": 3,
  "name": "Example Extension",
  "version": "1.0",
  "description": "This is an example extension.",
  "permissions": ["storage"],
  "icons": {
      "16": "images/16.png",
      "48": "images/48.png",
      "64": "images/64.png",
      "128": "images/128.png"
  },
  "options_ui": {
    "page": "options.html"
  },
"host_permissions":[ "https://www.example.com/api/post"],
    "content_scripts": [
    {
      "matches": [
        "https://www.example-target-url.com"],
      "js": ["assets/jquery-3.7.1.min.js","assets/content.js"],
      "run_at": "document_idle"
    }
  ]
}

My Script File (content.js):

$(document).ready(function() {
    setTimeout(
        function() {

                var table = $('tbody > tr'); // target table

                $.each(table, function(key, value) {
                    var number = $(this).find('span.number__container')[0];
                    number = number.innerText;


                    var targetField = $(this).find('.target'); // last target class
                    var button = "<button id='createButton_" + key + "' value='" + number + "' class='btn btn-block secondary-button btn-mp-secondary'>+ Create</button>";
                    targetField.append(button).html();

                    $('#createButton_' + key).on('click', function() {

                        $('#createButton_' + key).prop('disabled', true).text('Creating...');

                        var settings = {
                            "url": "https://www.example.com/api/post",
                            "method": "POST",
                            "timeout": 0,
                            "data": {
                                "name": licenseId,
                                "number": number
                            }
                        };
                        $.ajax(settings).done(function(response) {
                            var obj = JSON.parse(response);
                            if (obj.code == 200) {
                                $('#createButton_' + key).addClass('btn btn-block secondary-button btn-mp-success').text('Success!');
                            } else {
                                $('#createButton_' + key).text('Not Created!');
                                window.alert(obj.content);
                            }
                        });
                    })
                })
        }, 2000);
});

The extension works properly when the buttons appears. My “Create” buttons are showing sometimes and working but It disappears when I refresh the page. When I try again, it still doesn’t appear. For example, when I try for the third time, all buttons appears.

Extension not working stably. Can you help me on what should I do?

Thanks.

I tried;

  • Timeout function
  • runs_at: document_idle

Why am I getting “Uncaught DOMException: failed to execute add on DOMTokenList”

I am getting this error for some reasonenter image description here
And this one => enter image description here

I believe this error has something to do with my changing the mode from light mode to dark mode. Here is what that function looks like in my navbar.jsx => “

// function to toggle between dark mode / light
  const toggleTheme = () => {
    setTheme((prevTheme) => (prevTheme === "light" ? "dark" : "light"));
  };"


   <div id="navbar-container" className={`flex justify-between z-10 items-center top-0 pt-3 px-4 w-full sticky ${theme === "dark" ? "bg-slate-950": "bg-white"}`}>

Here is my App.jsx where the themeprovider is located (I use shadcn-ui for the themeprovider) =>

const Navigation = () => {
  const location = useLocation();
  const loginRoute = location.pathname === '/login';
  const emailConfirmRoute = location.pathname === "/success/confirm";

  // Determine which component to render based on the route
  const renderNavbar = loginRoute || emailConfirmRoute ? null : (location.pathname === '/' ? <Navbar /> : <DashboardNavbar />);
  

  return renderNavbar;
};

const FooterComponent = () => {
  const location = useLocation();
  const loginRoute = location.pathname === '/login';

  const renderFooter = loginRoute ? null : (location.pathname === '/' ? <Footer /> : null);
  
  return renderFooter;
};

// Create context for the user
export const UserContext = createContext(null);

// Custom hook to use the user context
export const useUser = () => useContext(UserContext);

const App = () => {
  const [user, setUser] = useState(null);

  // useEffect for auth to determine if user is authenticated or not
  useEffect(() => {
    // Define an async function to get the session
    async function getSession() {
      try {
        // Wait for the session promise to resolve
        const {data: { session }} = await supabase.auth.getSession()
  
        // If there is a session, set the user state to the session's user information
        if (session) {
          console.log("Session object:", session);
        
        if (session.user && session.user.aud) {
          console.log("Session aud:", session.user?.aud)
        } else {
          console.log("Session is undefined")
        }
        setUser(session.user);
        
      } else {
          console.log('No active session: User is not logged in');
        }
      } catch (error) {
        console.error('Error fetching session:', error);
      }
    }
    // Call the async function
    getSession();
  }, [setUser]);

  return (
    <ThemeProvider defaultTheme='light' storageKey='vite-ui-theme'>
      <UserContext.Provider value={{ user, setUser }}>
        <Router>
          <div>
            {/* Render the appropriate component based on the route */}
            <Navigation/>
            <Routes>
              <Route path="/" element={<Home />} />
              <Route path='/create' element={<Dashboard />} />
              <Route path='/login' element={<Login />} />
              <Route path='/success/confirm' element={<ConfirmEmail />} />
            </Routes>
            <FooterComponent />
          </div>
        </Router>
      </UserContext.Provider>
    </ThemeProvider>
  );
};

export default App;"

And the themeprovider.jsx =>

/* eslint-disable react/prop-types */
import { createContext, useContext, useEffect, useState } from "react";

const ThemeProviderContext = createContext(null);

export function ThemeProvider({
  children,
  defaultTheme = "system",
  storageKey = "vite-ui-theme",
  ...props
}) {
  const [theme, setTheme] = useState(
    () => localStorage.getItem(storageKey) || defaultTheme
  );

  useEffect(() => {
    const root = window.document.documentElement;

    root.classList.remove("light", "dark");

    if (theme === "system") {
      const systemTheme = window.matchMedia("(prefers-color-scheme: dark)")
        .matches
        ? "dark"
        : "light";

      root.classList.add(systemTheme);
      return;
    }

    root.classList.add(theme);
  }, [theme]);

  const value = {
    theme,
    setTheme: (theme) => {
      localStorage.setItem(storageKey, theme);
      setTheme(theme);
    },
  };

  return (
    <ThemeProviderContext.Provider {...props} value={value}>
      {children}
    </ThemeProviderContext.Provider>
  );
}

// eslint-disable-next-line react-refresh/only-export-components
export const useTheme = () => {
  const context = useContext(ThemeProviderContext);

  if (context === undefined)
    throw new Error("useTheme must be used within a ThemeProvider");

  return context;
};

Now the weird part => This error only happens when I am logged in on my app which uses supabase for authentication. For example when I clear my browser cahce or check out the app in icognito, everything works as expected including changing from light to dark theme and vice versa.
This means that something is going on with my authentication that is causing this error.

Any help would be much appreciated. Genuinly don’t know where to look to figure this out.