User: In my AI assistant interface website currently, adding a new chat opens the home page rather than going to that newly created chat. How do I fix this?<div><br></div><code fileName="ChatContext.js" notes="">// src/context/ChatContext.js
import React, { createContext, useState, useEffect } from &#039;react&#039;;
import { v4 as uuidv4 } from &#039;uuid&#039;;

export const ChatContext = createContext();

export const ChatProvider = ({ children }) =&gt; {
  const [chats, setChats] = useState(() =&gt; {
    const saved = localStorage.getItem(&#039;chats&#039;);
    return saved ? JSON.parse(saved) : [];
  });

  useEffect(() =&gt; {
    const saved = localStorage.getItem(&#039;chats&#039;);
    if (saved) {
      const parsedChats = JSON.parse(saved).map(chat =&gt; ({
        ...chat,
        messages: chat.messages.map(msg =&gt; ({
          ...msg,
          text: String(msg.text) // Ensure text is string
        }))
      }));
      setChats(parsedChats);
    } else {
      setChats([]);
    }
  }, []);

  const [currentChatId, setCurrentChatId] = useState(() =&gt; {
    const saved = localStorage.getItem(&#039;currentChatId&#039;);
    return saved ? JSON.parse(saved) : null;
  });

  const [models, setModels] = useState([]); // List of available models
  const [selectedModelId, setSelectedModelId] = useState(() =&gt; {
    const saved = localStorage.getItem(&#039;selectedModelId&#039;);
    return saved ? JSON.parse(saved) : null;
  });

  // Fetch models from the backend on component mount
  useEffect(() =&gt; {
    fetch(&#039;http://localhost:8000/api/models&#039;)
      .then((res) =&gt; {
        if (!res.ok) {
          throw new Error(`HTTP error! Status: ${res.status}`);
        }
        return res.json();
      })
      .then((data) =&gt; {
        console.log(&#039;Fetched models:&#039;, data); // Debugging line
        if (Array.isArray(data) &amp;&amp; data.length &gt; 0 &amp;&amp; !selectedModelId) {
          setSelectedModelId(data[0].id); // Select the first model by default
        }
        setModels(data);
      })
      .catch((error) =&gt; {
        console.error(&#039;Error fetching models:&#039;, error);
        setModels([]); // Prevent `.map` errors
      });
  }, []);

  // Persist chats to localStorage
  useEffect(() =&gt; {
    localStorage.setItem(&#039;chats&#039;, JSON.stringify(chats));
  }, [chats]);

  // Persist currentChatId to localStorage
  useEffect(() =&gt; {
    localStorage.setItem(&#039;currentChatId&#039;, JSON.stringify(currentChatId));
  }, [currentChatId]);

  // Persist selectedModelId to localStorage
  useEffect(() =&gt; {
    if (selectedModelId) {
      localStorage.setItem(&#039;selectedModelId&#039;, JSON.stringify(selectedModelId));
    }
  }, [selectedModelId]);

  const addChat = (name = `Chat ${chats.length + 1}`) =&gt; {
    const newChat = {
      id: uuidv4(),
      name: name,
      messages: [],
      systemPrompt: &#039;&#039;,
      model_id: selectedModelId, // Associate with selected model
    };
    setChats((prev) =&gt; [newChat, ...prev]);
    setCurrentChatId(newChat.id);
  };  

  const updateChat = (id, updatedChat) =&gt; {
    console.log(`Updating chat with ID: ${id}`, updatedChat); // Add this line
    setChats((prevChats) =&gt;
      prevChats.map((chat) =&gt; (chat.id === id ? { ...chat, ...updatedChat } : chat))
    );
  };

  const addMessage = (id, message) =&gt; {
    setChats((prevChats) =&gt;
      prevChats.map((chat) =&gt;
        chat.id === id
          ? { ...chat, messages: [...chat.messages, { ...message, text: String(message.text) }] }
          : chat
      )
    );
  };

  const deleteChat = (id) =&gt; {
    setChats((prevChats) =&gt; prevChats.filter((chat) =&gt; chat.id !== id));
    // If the deleted chat was the current one, reset currentChatId
    if (id === currentChatId) {
      setCurrentChatId(null);
    }
  };

  const clearChats = () =&gt; {
    setChats([]);
    setCurrentChatId(null);
  };

  const updateMessage = (chatId, messageIndex, updatedMessage) =&gt; {
    setChats((prevChats) =&gt;
      prevChats.map((chat) =&gt;
        chat.id === chatId
          ? {
              ...chat,
              messages: chat.messages.map((msg, idx) =&gt;
                idx === messageIndex
                  ? { ...msg, text: String(updatedMessage.text) }
                  : msg
              ),
            }
          : chat
      )
    );
  };

  const addModel = (model) =&gt; {
    setModels((prev) =&gt; [...prev, model]);
  };

  const removeModel = (modelId) =&gt; {
    setModels((prev) =&gt; prev.filter((model) =&gt; model.id !== modelId));
    // Optionally, handle chat associations if the removed model was in use
    if (selectedModelId === modelId) {
      setSelectedModelId(models.length &gt; 0 ? models[0].id : null);
    }
  };

  return (
    &lt;ChatContext.Provider
      value={{
        chats,
        currentChatId,
        setCurrentChatId,
        addChat,
        updateChat,
        addMessage,
        updateMessage,
        deleteChat,
        clearChats,
        models,
        addModel,
        removeModel,
        selectedModelId,
        setSelectedModelId,
      }}
    &gt;
      {children}
    &lt;/ChatContext.Provider&gt;
  );
};
</code><code fileName="Sidebar.js" notes="">// src/components/Sidebar.js
import React, { useContext, useState } from &quot;react&quot;;
import { ChatContext } from &quot;../context/ChatContext&quot;;
import { PlusIcon, TrashIcon } from &quot;@heroicons/react/solid&quot;;
import { ThemeContext } from &quot;../context/ThemeContext&quot;;
import ChatItem from &quot;./ChatItem&quot;;
import DarkModeToggle from &quot;./DarkModeToggle&quot;;
import ConfirmModal from &quot;./ConfirmModal&quot;;
import ModelList from &quot;./ModelList&quot;; // Import the ModelList component
import Favicon from &quot;../assets/favicon.png&quot;

function Sidebar() {
  const {
    chats,
    currentChatId,
    setCurrentChatId,
    addChat,
    deleteChat,
    updateChat,
    clearChats,
    models,
  } = useContext(ChatContext);

  const { theme, toggleTheme } = useContext(ThemeContext);

  const [isResetting, setIsResetting] = useState(false);
  const [error, setError] = useState(null);
  const [isModalOpen, setIsModalOpen] = useState(false); // For deleting all chats

  const handleNewChat = async () =&gt; {
    setIsResetting(true);
    setError(null);

    try {
      const response = await fetch(&quot;http://localhost:8000/api/reset&quot;, {
        method: &quot;POST&quot;,
        headers: {
          &quot;Content-Type&quot;: &quot;application/json&quot;,
        },
      });

      if (!response.ok) {
        throw new Error(&quot;Failed to reset chat.&quot;);
      }

      const data = await response.json();
      console.log(data.status);

      addChat(&quot;New Chat&quot;);
      setCurrentChatId(null);
    } catch (err) {
      console.error(&quot;Error resetting chat:&quot;, err);
      setError(&quot;Unable to reset the chat. Please try again.&quot;);
    } finally {
      setIsResetting(false);
    }
  };

  const handleGoHome = () =&gt; {
    setCurrentChatId(null);
  };

  const handleDeleteAllChats = () =&gt; {
    setIsModalOpen(true);
  };

  const confirmDeleteAllChats = () =&gt; {
    clearChats();
    setIsModalOpen(false);
  };

  const cancelDeleteAllChats = () =&gt; {
    setIsModalOpen(false);
  };

  return (
    &lt;div className=&quot;w-72 bg-gray-100 dark:bg-zinc-900 border-r dark:border-gray-700 p-4 flex flex-col&quot;&gt;
      {/* Chatbot Name &quot;Echo&quot; at the top */}
      &lt;div
        className=&quot;mb-6 text-2xl font-bold text-gray-800 dark:text-gray-200 cursor-pointer flex flex-row align-middle&quot;
        onClick={handleGoHome}
      &gt;
      &lt;img src={Favicon} alt=&quot;Logo of Echo&quot; width={&quot;32&quot;} className=&quot;mr-2 mt-[2px]&quot; /&gt;
        Echo
      &lt;/div&gt;

      &lt;div className=&quot;flex justify-between items-center mb-4&quot;&gt;
        &lt;h2 className=&quot;text-xl font-bold text-gray-800 dark:text-gray-200&quot;&gt;
          Past Chats
        &lt;/h2&gt;
        &lt;button
          onClick={handleNewChat}
          className={`p-2 bg-blue-500 text-white rounded hover:bg-blue-600 flex items-center justify-center ${
            isResetting ? &quot;opacity-50 cursor-not-allowed&quot; : &quot;&quot;
          }`}
          title=&quot;Start New Chat&quot;
          disabled={isResetting}
        &gt;
          {isResetting ? &quot;Resetting...&quot; : &lt;PlusIcon className=&quot;h-5 w-5&quot; /&gt;}
        &lt;/button&gt;
      &lt;/div&gt;

      {error &amp;&amp; &lt;div className=&quot;mb-4 text-red-500 text-sm&quot;&gt;{error}&lt;/div&gt;}

      &lt;ul className=&quot;flex-1 overflow-y-auto space-y-2&quot;&gt;
        {chats.length === 0 &amp;&amp; (
          &lt;li className=&quot;text-gray-500 dark:text-gray-400&quot;&gt;No past chats.&lt;/li&gt;
        )}
        {chats.map((chat) =&gt; (
          &lt;ChatItem key={chat.id} chat={chat} /&gt;
        ))}
      &lt;/ul&gt;

      {/* Delete All Chats Button */}
      {chats.length &gt; 0 &amp;&amp; (
        &lt;button
          onClick={handleDeleteAllChats}
          className=&quot;mt-4 p-2 bg-red-500 text-white rounded hover:bg-red-600 flex items-center justify-center&quot;
          title=&quot;Delete All Chats&quot;
        &gt;
          &lt;TrashIcon className=&quot;h-5 w-5&quot; /&gt;
          &lt;span className=&quot;ml-2&quot;&gt;Delete All&lt;/span&gt;
        &lt;/button&gt;
      )}

      {/* Confirm Modal */}
      {isModalOpen &amp;&amp; (
        &lt;ConfirmModal
          title=&quot;Delete All Chats&quot;
          message=&quot;Are you sure you want to delete all chats? This action cannot be undone.&quot;
          onConfirm={confirmDeleteAllChats}
          onCancel={cancelDeleteAllChats}
        /&gt;
      )}

      {/* Model List */}
      &lt;ModelList /&gt;

      {/* Dark Mode Toggle at the bottom */}
      &lt;div className=&quot;mt-4&quot;&gt;
        &lt;DarkModeToggle theme={theme} toggleTheme={toggleTheme} /&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  );
}

export default Sidebar;</code>