FredrikOseberg / react-chatbot-kit

MIT License
324 stars 154 forks source link

How can I access state in CustomComponents declared in config.js #161

Open Namanbhatia7 opened 10 months ago

Namanbhatia7 commented 10 months ago

I want to access state in customBotMessage so that I can handle loader passed through props in it. `#Config.js

import { createChatBotMessage } from 'react-chatbot-kit'; import ChatbotHeader from './CustomComponents/CustomHeader'; import CustomBotAvatar from './CustomComponents/CustomBotAvatar'; import CustomBotMessage from './CustomComponents/CustomBotMessage';

const config = { initialMessages: [createChatBotMessage(Hello world)], state: { isLoading: false }, customComponents: { header: (props) => <ChatbotHeader {...props} />, botAvatar: (props) => <CustomBotAvatar {...props} />, botChatMessage: (props) => <CustomBotMessage {...props} /> }, };

export default config;

`

` import React, { useEffect, useState } from 'react'; import '../index.css';

const CustomBotMessage = (props) => { const [loading, setLoading] = useState(true);

useEffect(() => {
    setLoading(true);
    if (props.message) {
    setLoading(false);
    }
}, [props.message]);

return (
    <div className="react-chatbot-kit-chat-bot-message">
        { loading? props.loader : <span>{props.message}</span>}
    <div className="react-chatbot-kit-chat-bot-message-arrow"></div>
    </div>
);

};

export default CustomBotMessage;

` import React from 'react'; import { getBotResponse } from '../../api';

const ActionProvider = ({ createChatBotMessage, setState, children }) => { const handleUserResponse = (message) => { let messageOutput = ""; const bot_payload = { query: message, conversation_id: "test_id" } setState((prev) => ({ ...prev, isLoading: true, })); getBotResponse(bot_payload) .then((data) => { messageOutput = data console.log(data) let botMessage = createChatBotMessage(messageOutput) setState((prev) => ({ ...prev, messages: [...prev.messages, botMessage], isLoading: false }));

})
.catch((err) => {
  console.log(err)
})  

}

// Put the handleHello function in the actions object to pass to the MessageParser return (

{React.Children.map(children, (child) => { return React.cloneElement(child, { actions: { handleUserResponse, }, }); })}

); };

export default ActionProvider;

` So , Basically based on setState in actionProvider, I want to render a loader in customBotMessage but for that I am not sure how to access state inside customComponents.

tech-alpinist commented 10 months ago

If you want to pass data to custom widgets, you can do with props of widget.