{showLinkModal && (
Enter PDF Link
<input
type="text"
className="w-full border border-gray-300 p-2 rounded-lg mb-4"
placeholder="Enter PDF link here..."
value={pdfLink}
onChange={(e) => setPdfLink(e.target.value)}
/>
<button
className="mr-2 bg-gray-300 px-4 py-2 rounded-lg"
onClick={() => setShowLinkModal(false)}
>
Cancel
Upload
)}
Instead of one I want two text
Assistant
To modify your modal so that it includes two input fields instead of one, you can expand upon the current structure. You would want to add another input element and also manage the state for the second input. Below is an example of how you can achieve this:
javascript
User
// Handle document comparison via link
const handleDocumentComparison = async () => {
if (!pdfLink1) {
alert("Please enter a valid PDF link.");
return;
}
if (!pdfLink2) {
alert("Please enter a valid PDF link.");
return;
}
code
Assistant
User
Analyse Document1: {pdfLink1} \n Document2: {pdfLink2} Correct in react js
Assistant
In React, if you want to create a line of text that includes variables such as pdfLink1 and pdfLink2, you can use template literals with the JavaScript string interpolation feature within JSX. Here's how you can do it correctly:
Using Template Literals in JSX
You can directly embed JavaScript expressions within curly braces {} in JSX. Here's an example of how to format your string with the given variables:
jsx
User
I want it in a string
Assistant
If you want to create a string that includes values from pdfLink1 and pdfLink2, you can use template literals in JavaScript to construct that string. Here's how you can do it in a React component:
{showLinkModal && (
<div className="fixed inset-0 flex items-center justify-center bg-gray-800 bg-opacity-50">
<div className="bg-white p-8 rounded-lg shadow-lg w-2/3">
<h2 className="text-lg font-semibold mb-4">Enter PDF Links</h2>
{/* First Input Field */}
<input
type="text"
className="w-full border border-gray-300 p-2 rounded-lg mb-4"
placeholder="Enter first PDF link here..."
value={pdfLink1}
onChange={(e) => setPdfLink1(e.target.value)}
/>
{/* Second Input Field */}
<input
type="text"
className="w-full border border-gray-300 p-2 rounded-lg mb-4"
placeholder="Enter second PDF link here..."
value={pdfLink2}
onChange={(e) => setPdfLink2(e.target.value)}
/>
<div className="flex justify-end">
<button
className="mr-2 bg-gray-300 px-4 py-2 rounded-lg"
onClick={() => setShowLinkModal(false)}
>
Cancel
</button>
<button
className="bg-blue-500 text-white px-4 py-2 rounded-lg"
onClick={handleLinkUpload}
>
Upload
</button>
</div>
</div>
</div>
)}
Changes Made:
State Variables: You need to create two state variables (pdfLink1 and pdfLink2) to store the links entered in the two input fields.
Despite response being 200 in backend, its saying error in alert in UI
When your UI is alerting an error even though you are receiving a 200 OK response from the backend, the issue may lie in how you are handling the server response. Here are a few steps to debug and ensure you handle responses correctly:
Review of Your Code:
Ensure Proper Response Handling:
After making the fetch request, you should check the response status or if the response contains the expected data. A 200 OK response doesn't always mean that the operation was successful; the body of the response may indicate success or failure.
Modify your handleDocumentComparison function:
javascript
const handleDocumentComparison = async () => {
if (!pdfLink1) {
alert("Please enter a valid PDF link.");
return;
}
if (!pdfLink2) {
alert("Please enter a valid PDF link.");
return;
}
let index = -1;
setMessages((prevMessages) => {
index = prevMessages.length;
return [...prevMessages, { message: "", prompt: "" }];
});
console.log(messages);
setShowCompareModal(false);
try {
const response = await fetch(baseurl + "/compare-documents", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
pdf_url_1: pdfLink1,
pdf_url_2: pdfLink2,
user_email: JSON.parse(localStorage.getItem("user")).email,
}),
});
// Check if response is successful
if (!response.ok) {
const errorResponse = await response.json(); // or response.text() based on your backend
throw new Error(errorResponse.message || "An error occurred");
}
const reader = response.body.getReader();
const decoder = new TextDecoder("utf-8");
while (true) {
const { value, done } = await reader.read();
if (done) break;
const chunk = decoder.decode(value, { stream: true });
setMessages((prevMessages) => {
const updatedMessages = [...prevMessages];
if (!updatedMessages[index].api_output) {
updatedMessages[index].api_output = { text: "" };
}
updatedMessages[index].api_output.text += chunk;
return updatedMessages;
});
}
} catch (error) {
console.log("Error in getting response:", error);
alert(`Error in generating response: ${error.message}`);
}
};
Key Updates:
Response Status Check:
After the fetch request, use the response.ok property to check if the response status is in the range of 200-299 (indicating a successful request). If not, throw an error with a relevant message.
Error Handling:
Catch any errors that occur and provide a more detailed error message using error.message if it exists or a fallback string.
Logging:
In your catch block, you're already logging the error, which is good for debugging. Make sure to also log error.response or similar if there's additional context.
Additional Consideration:
Backend Response Format: Ensure that your backend responds with a JSON object when there's an error, and that the error message is accessible via errorResponse.message. If not, adjust the error handling accordingly so it catches network errors or parsing errors properly.
By implementing these adjustments, you should have a more reliable mechanism for detecting and displaying errors based on the actual response received from the backend.
{/* Assuming pdfLink1 and pdfLink2 are defined and contain the PDF links */}
<p>
{`Analyse Document1: ${pdfLink1} \n Document2: ${pdfLink2}`}
</p>
Important Note on New Lines
However, you might notice that \n will not actually create a new line in HTML. To create a line break in JSX rendered HTML, you should use the <br /> tag instead. Here's how to achieve that:
jsx
{/* Assuming pdfLink1 and pdfLink2 are defined and contain the PDF links */}
<div>
<p>Analyse Document1: {pdfLink1}</p>
<p>Document2: {pdfLink2}</p>
</div>
Use {} to include JavaScript expressions within JSX.
Use <br /> for line breaks in HTML instead of \n.
When displaying dynamic text, wrapping it in paragraph tags or divs is always a good practice for better semantics and flexibility in styling.
Creating a String in a React Component
You can create a string where you interpolate the variable values directly like this:
jsx
import React from "react";
const DocumentAnalysis = ({ pdfLink1, pdfLink2 }) => {
// Create the string using template literals
const analysisString = `Analyse Document1: ${pdfLink1}\nDocument2: ${pdfLink2}`;
// You can display the string in a <pre> tag to preserve the formatting
return (
<div>
<pre>{analysisString}</pre>
</div>
);
};
export default DocumentAnalysis;
// Usage Example
// <DocumentAnalysis pdfLink1="http://example.com/doc1.pdf" pdfLink2="http://example.com/doc2.pdf" />
Explanation:
Template Literals:
You use backticks (`) to create the string, allowing you to easily interpolate variables using ${variableName} syntax.
New Line:
The \n character is included in the string to indicate a new line. However, note that when displayed in a standard HTML element like a <div>, it won’t create a new line visually. Using a <pre> tag will make sure that the new line is rendered as expected in your UI.
Rendering:
By using the <pre> tag, the text will retain both spaces and line breaks, displaying it as intended.
If you only want the string for some other purpose (like logging it or sending it somewhere), then simply use the created string without rendering it in the JSX.
Example of Using the String for Other Operations
If you just want to construct the string without displaying it, you can do something like this:
jsx
import React from "react";
const DocumentAnalysis = ({ pdfLink1, pdfLink2 }) => {
// Constructing the string
const analysisString = `Analyse Document1: ${pdfLink1}\nDocument2: ${pdfLink2}`;
// Example usage: logging the string
console.log(analysisString);
return null; // or any other UI component you want to render
};
export default DocumentAnalysis;
This way, you can keep the functionality aimed purely at handling and utilizing the string as needed without rendering it on the screen.