tjtanjin / react-chatbotify

A modern React library for creating a flexible and extensible chatbot.
https://react-chatbotify.com
MIT License
148 stars 68 forks source link

writting one dispatch or setState when response coming react-chatbotify automatically closing #88

Closed ajaysingh7623 closed 1 month ago

ajaysingh7623 commented 1 month ago

async function run(params) { const authToken = localStorage.getItem("authToken"); const payload = { userinput: params?.userInput, history: { quote: "14235436" // quoteID: quoteID ||"" } }; const url = "/api/start"; const config = { headers: { "Content-Type": "application/json", Authorization: Bearer ${authToken} } }; try { const response = await axios.post(url, payload, config); // const quote = response?.data?.session_history.quote; // const quoteID = response?.data?.session_history.quoteID; // setSessionHistory((prev) => ({ // ...prev, // quote: quote, // quoteID: quoteID // })); dispatch({ type: "SET_SESSION_HISTORY", payload: response?.data?.session_history }); if (response.data) { params.streamMessage( response?.data?.bot_response + " " + response?.data?.next_step_recommendation);

    } else {
      console.error("Unexpected response structure:", response);
      return "Unexpected response from server.";
    }
} catch (error) {
  console.error("Error during Axios request:", error);
  return "An error occurred while processing your request.";
}

} const flow = { start: { message: "Hello, I am CPQ ChatBot, How Can I Help You!", path: "model_loop" }, model_loop: { message: (params) => { run(params); }, path: "model_loop" } }; if i don't use dispatch or setState then it is working fine. @tjtanjin please check

tjtanjin commented 1 month ago

Hey @ajaysingh7623, the usage of useState works as shown in this example: https://react-chatbotify.com/docs/examples/basic_form

It might have to do with how you've setup your redux store as well - I can't be sure but I'm afraid this is not an issue related to the library.

ajaysingh7623 commented 1 month ago

import axios from "axios"; import { CDN_LOTTIES } from "config/env"; import React, { useState } from "react"; import ChatBot from "react-chatbotify"; import { useDispatch } from "react-redux"; function ChatBotify() { const dispatch = useDispatch(); const [quote, setQuote] = useState(""); // Select the session history from the Redux store // const {quote,quoteID} = useSelector((state) => state.chatBotifyReducer); console.log(quote, "session");

// const [sessionHistory, setSessionHistory] = useState({ // quote: "", // quoteID: "" // }); // console.log(sessionHistory, "hh"); async function run(params) { const authToken = localStorage.getItem("authToken"); const payload = { userinput: params?.userInput, history: { quote: "14235436", quoteID: quote ||"" } }; const url = "/api/start"; const config = { headers: { "Content-Type": "application/json", Authorization: Bearer ${authToken} } }; try { const response = await axios.post(url, payload, config); const quote = response?.data?.session_history.quote; const quoteID = response?.data?.session_history.quoteID; setQuote(quoteID); // setSessionHistory((prev) => ({ // ...prev, // quote: quote, // quoteID: quoteID // })); // dispatch({ // type: "SET_SESSION_HISTORY", // payload: response?.data?.session_history // }); if (response.data) { params.streamMessage( response?.data?.bot_response + " " + response?.data?.next_step_recommendation ); } else { console.error("Unexpected response structure:", response); return "Unexpected response from server."; } } catch (error) { console.error("Error during Axios request:", error); return "An error occurred while processing your request."; } } const flow = { start: { message: "Hello, I am CPQ ChatBot, How Can I Help You!", path: "model_loop" }, model_loop: { message: (params) => { run(params); }, path: "model_loop" } };

const themes = [ { id: "solid_purple_haze", version: "0.1.0" }, { id: "minimal_midnight", version: "0.1.0" } ]; const microsoftLogo = ${CDN_LOTTIES.replace( "lotties", "images" )}microsoft-edge.png; const styles = { // chatButtonStyle: { // height: "10%", // width: "10%" // } };

return ( <ChatBot themes={themes} styles={styles} settings={{ audio: { disabled: false, defaultToggledOn: false }, voice: { disabled: false }, chatHistory: { storageKey: "example_audio" }, chatButton: { icon: microsoftLogo } }} flow={flow} /> ); } export default ChatBotify; @tjtanjin even with the string usestate it is happening

ajaysingh7623 commented 1 month ago

when i am using state there is multiple calls happening from react-chatbotify but if i dont use state then there is one call happening that is api call as you can see in this gif.

tjtanjin commented 1 month ago

when i am using state there is multiple calls happening from react-chatbotify but if i dont use state then there is one call happening that is api call

// image removed as requested

as you can see in this gif.

Hmm just noticed you have themes declared. Does removing themes make a difference?

ajaysingh7623 commented 1 month ago

@tjtanjin i got it is happening with themes

ajaysingh7623 commented 1 month ago

thank you @tjtanjin

ajaysingh7623 commented 1 month ago

@tjtanjin themes are creating issues like closing automatically chatbotify is there any update happening in this. so this fix can help us to show our chatbotify beautifull?

tjtanjin commented 1 month ago

@tjtanjin themes are creating lot of issues like closing automatically chatbotify is there any update so this fix can be happen soon?

I have a good guess of where the issue for closing automatically is. Could you share what the other lot of issues are so I can look at them?

ajaysingh7623 commented 1 month ago

for now state thing happening and closing of chatbotify automatically. is there any update coming for theme?

tjtanjin commented 1 month ago

for now state thing happening and closing of chatbotify automatically.

Both are actually caused by the config parser for themes. I can probably get a fix out fast.

tjtanjin commented 1 month ago

@ajaysingh7623 You can try updating to v2.0.0-beta.3, the issue is fixed, thanks for surfacing it!

ajaysingh7623 commented 1 month ago

@tjtanjin now also multiple calls of css,setting is happening in network and chatbotify is closing automatically

tjtanjin commented 1 month ago

@tjtanjin now also multiple calls of css,setting is happening in network and chatbotify is closing automatically

Have you double checked that you've properly updated to the latest beta version? It should show 2.0.0-beta.3 in package.json or if you're unsure, delete the entire node_modules folder and do a clean npm install.

Edit: In case you're wondering, network calls are expected, that's how themes work by fetching the relevant settings and styles.

ajaysingh7623 commented 1 month ago

@tjtanjin now also multiple calls of css,setting is happening in network and chatbotify is closing automatically

Have you double checked that you've properly updated to the latest beta version? It should show 2.0.0-beta.3 in package.json or if you're unsure, delete the entire node_modules folder and do a clean npm install.

Edit: In case you're wondering, network calls are expected, that's how themes work by fetching the relevant settings and styles.

@tjtanjin yes first i uninstalled and then i installed what you suggested and checked in incognito mode

tjtanjin commented 1 month ago

@tjtanjin now also multiple calls of css,setting is happening in network and chatbotify is closing automatically

Have you double checked that you've properly updated to the latest beta version? It should show 2.0.0-beta.3 in package.json or if you're unsure, delete the entire node_modules folder and do a clean npm install. Edit: In case you're wondering, network calls are expected, that's how themes work by fetching the relevant settings and styles.

@tjtanjin yes first i uninstalled and then i installed what you suggested and checked in incognito mode image

It's hard to debug without access to your project, but you can do a quick check as follows: 1) Clone the React ChatBotify Repository 2) Run npm install 3) Replace the following test code into App.tsx:

import React from "react";
import ChatBot from "./components/ChatBot";
import { Flow } from "./types/Flow";
import { Params } from "./types/Params";

function App() {

    const [themes, setThemes] = React.useState([{id: "hamilton"}]);
    const [testString, setTestString] = React.useState("");

    // Serves as an example flow used during the development phase - covers all possible attributes in a block.
    // restore to default state before running selenium tests (or update the test cases if necessary)!
    const flow: Flow = {
        start: {
            message: "Hello! What is your name?",
            path: "ask_age_group",
        },
        ask_age_group: {
            message: (params: Params) => {
                setTestString("Test");
                console.log(testString);
                return `Hey ${params.userInput}! Nice to meet you, what is your age group?`
            },
            options: ["child", "teen", "adult"],
            chatDisabled: true,
            path: () => "ask_math_question",
        },
        ask_math_question: {
            message: (params: Params) => {
                if (params.prevPath == "incorrect_answer") {
                    return;
                }
                return `I see you're a ${params.userInput}. Let's do a quick test! What is 1 + 1?`
            },
            path: (params: Params) => {
                if (params.userInput != "2") {
                    return "incorrect_answer"
                } else {
                    return "ask_favourite_color";
                }
            },
        },
        ask_favourite_color: {
            message: "Great Job! What is your favourite color?",
            path: "ask_favourite_pet"
        },
        ask_favourite_pet: {
            message: "Interesting! Pick any 2 pets below.",
            checkboxes: {items: ["Dog", "Cat", "Rabbit", "Hamster"], min:2, max: 2},
            function: (params: Params) => alert(`You picked: ${JSON.stringify(params.userInput)}!`),
            path: "ask_height",
        },
        ask_height: {
            message: "What is your height (cm)?",
            path: (params: Params) => {
                if (isNaN(Number(params.userInput))) {
                    params.injectMessage("Height needs to be a number!");
                    return;
                }
                return "ask_weather";
            }
        },
        ask_weather: {
            message: (params: Params) => {
                if (params.prevPath == "incorrect_answer") {
                    return;
                }
                return "What's my favourite color? Click the button below to find out my answer!"
            },
            component: (
                <div style={{
                    width: "100%",
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "center",
                    marginTop: 10
                }}>
                    <button 
                        className="secret-fav-color"
                        onClick={() => alert("black")}>
                        Click me!
                    </button>
                </div>
            ),
            path: (params: Params) => {
                if (params.userInput.toLowerCase() != "black") {
                    return "incorrect_answer"
                } else {
                    params.openChat(false);
                    return "close_chat";
                }
            },
        },
        close_chat: {
            message: "I went into hiding but you found me! Ok tell me, what's your favourite food?",
            path: "ask_image"
        },
        ask_image: {
            message: (params: Params) => `${params.userInput}? Interesting. Could you share an image of that?`,
            file: (params: Params) => console.log(params.files),
            path: "end"
        },
        end: {
            message: "Thank you for sharing! See you again!",
            path: "loop"
        },
        loop: {
            message: "You have reached the end of the conversation!",
            path: "loop"
        },
        incorrect_answer: {
            message: "Your answer is incorrect, try again!",
            transition: {duration: 0},
            path: (params: Params) => params.prevPath
        },
    }

    return (
        <div className="App">
            <header className="App-header">
                <button onClick={() => setThemes([])}>Clear Themes</button>
                <div style={{display: "flex", justifyContent: "center", alignItems: "center", marginTop: `calc(20vh)`}}>
                    <ChatBot
                        flow={flow}
                        settings={{
                            audio: {disabled: false},
                            chatInput: {botDelay: 1000},
                            userBubble: {showAvatar: true},
                            botBubble: {showAvatar: true},
                            voice: {disabled: false},
                        }}
                        themes={themes}
                    ></ChatBot>
                </div>
            </header>
        </div>
    );
}

export default App;

3) Do npm run start, open the chatbot, then click on the "Clear Themes" button which will immediately refresh the theme. It should remain open.

You can also setup a whole new project locally and do a quick test. I'm not sure if you've tried deleting the whole node_modules folder to reinstall as a sanity check but that's what I'll probably try first.

ajaysingh7623 commented 1 month ago

@tjtanjin now this is working thank you.