chatengine-io / react-chat-engine

React component for a cheap and easy chat API
138 stars 35 forks source link

Issues using the Get or Create Chat API call #92

Closed PaoDLR closed 2 years ago

PaoDLR commented 2 years ago

Hi!

I've been trying to develop a mobile application where if a user clicks on the button on someone else's user profile, it will render the Chatengine chat between the currently logged-in user and the user of the current profile they are viewing.

Is that possible?

Here's how my code looks like. I've extracted the current chat_id of the chat between the two users and tried to render a chat between them only, but sadly it doesn't work. Any tips?

import React, { useEffect, useState } from "react";
import { ChatEngine, getOrCreateChat, getChat } from "react-chat-engine";
import ChatFeed from "../components/ChatFeed";
import NavigationBars from "../components/navigation-bars";
import Cookies from "universal-cookie";

import Axios from "axios";

const cookies = new Cookies();

Axios.defaults.headers.common = {
  "Content-Type": "application/json",
};

const baseUrl = "api";

const projectID = "b8862eee-ece1-48cb-a0a0-d700156de78e";

const PatientSideChat = (props) => {
  const authObject = {
    'Project-ID': 'b8862eee-ece1-48cb-a0a0-d700156de78e', 
    'User-Name': cookies.get("userData")[0].contactNumber, 
    'User-Secret': 'akasimed123!'
  }

  var config = {
    method: 'get',
    url: 'https://api.chatengine.io/chats/',
    headers: { 
      'Project-ID': 'b8862eee-ece1-48cb-a0a0-d700156de78e', 
      'User-Name': cookies.get("userData")[0].contactNumber, 
      'User-Secret': 'akasimed123!'
    }
  };

  console.log("Props in patient side chat", props);

  const [theirNumber, setTheirNumber] = useState("");
  const [doctorID, setDoctorID] = useState("");
  const [activeChat, setActiveChat] = useState("")
  const [firstnamePat, setfirstnamePat] = useState([])

  const firstNameDoc = cookies.get("userData")[0].fullName.split(" ")

  useEffect(() => {
    Axios.post(`${baseUrl}/get-doctor-userdata`, {
      fullName: props.location.state.doctorData.fullName,
    }).then((response) => {
      setTheirNumber([cookies.get("userData")[0].contactNumber, response.data[0].contactNumber]);
      setfirstnamePat(response.data[0].fullName.split(" "))
    });

    Axios.post(`${baseUrl}/doctor-data`, {
      fullName: props.location.state.doctorData.fullName,
    }).then((response) => {
      setDoctorID(response.data[0].doctor_ID);
    });

    Axios(config)
    .then(function (response) {
      console.log("RESPONSEDATA: ", response.data)
      setActiveChat(response.data)
    })
    .catch(function (error) {
      console.log(error);
    });

  }, []);

  const chat = {
    "usernames": 
    [cookies.get("userData")[0].contactNumber, 
    theirNumber]
  };

  const callback = (chat) => console.log(chat)

  function createDirectChat() {
    getOrCreateChat(authObject, { is_direct_chat: true, usernames: theirNumber},
            () => setTheirNumber('')
        )
  }

  function currentChat(){
    let temp = ""
    if(activeChat.length > 0){
      for(var i = 0; i < activeChat.length; i++){
        if(activeChat[i].title.includes(firstNameDoc[0]) && activeChat[i].title.includes(firstnamePat[0])){
          temp = activeChat[i].id
        }
      }
      getChat(authObject, temp)
    }
  }

  function currChatID(){
    let temp = ""
    if(activeChat.length > 0){
      for(var i = 0; i < activeChat.length; i++){
        if(activeChat[i].title.includes(firstNameDoc[0]) && activeChat[i].title.includes(firstnamePat[0])){
          temp = activeChat[i].id
        }
      }
    }

    return temp
  }

  return (
    <>
      <NavigationBars onclick={(e) => e.preventDefault()} />
      {theirNumber == "" ? null : (
        <ChatEngine
          height="100vh"
          projectID={projectID}
          userName={cookies.get("userData")[0].contactNumber}
          userSecret={"akasimed123!"}
          consult={props.location.state.inquiryData} //Inquiries Data
          doctorID={doctorID}
          activeChatID={currChatID()}
          doctorData={props.location.state.doctorData} //Doctor Data
          bidData={props.location.state.bidData} //Bid Data
          renderChatFeed={(chatAppProps) => <ChatFeed {...chatAppProps} />}
          renderNewChatForm={() => currentChat()}
        />
      )}
    </>
  );
};

export default PatientSideChat;

Any help would be greatly appreciated. Thanks!

alamorre commented 2 years ago

You need to involve all usernames in a list in the "usernames" field. Take a look at the example here: https://rest.chatengine.io/#4a596036-fd7c-4539-b913-52990c7847f9

Please let me know if this helps - it should 👍

PaoDLR commented 2 years ago

You need to involve all usernames in a list in the "usernames" field. Take a look at the example here: https://rest.chatengine.io/#4a596036-fd7c-4539-b913-52990c7847f9

Please let me know if this helps - it should 👍

Hey alamorre!

I have tried to include all usernames in the "usernames" field, but it does not do what I intend for it to do sadly and it also gives me a 403 error despite the correct project-id, user-name, and user-secret

The project that I have been trying to do is a mobile application, and I want to render the chat feed only; without looking at the chat list and selecting which user to chat with.

Is that possible? For it to render solely the chat feed of two users despite having multiple active chats?

alamorre commented 2 years ago

For inquires about using just the chat feed I would open a separate GitHub issue

This code snippet is rather long and confusing. Just try the getOrCreateChat call with just the code of interest and share it here

alamorre commented 2 years ago

Copy this format but with your own HARDCODED values to test:

var axios = require('axios');
var data = '{\n    "usernames": ["adam_la_morre", "bob_baker", "wendy_walker"],\n    "title": "Another Surprise Party!",\n    "is_direct_chat": false\n}';

var config = {
  method: 'put',
  url: 'https://api.chatengine.io/chats/',
  headers: { 
    'Project-ID': '{{project_id}}', 
    'User-Name': '{{user_name}}', 
    'User-Secret': '{{user_secret}}'
  },
  data : data
};

axios(config)
.then(function (response) {
  console.log(JSON.stringify(response.data));
})
.catch(function (error) {
  console.log(error);
});
alamorre commented 2 years ago

Following up - did any of this help?