โŒ

Normal view

There are new articles available, click to refresh the page.
Before yesterdayMain stream

useObserver hook doesn't work after re-render components

I have simple React app, that using two types of pagination: general by pages pagination and like twitter infinity pagination. For infinity pagination I used "useObserver" hook, to find the div element in the end of the page and if I see that element I load the next part of data. For general pagination I used general useState and general gooks. It doesn't matter. I want to dynamically switch between those two type of pagination by button click. I have two buttons: one button for pagination and second one for infinity pagination. When I clicked for the first one I render pages, when I pressed for the second one I re-render end of the page and remove pages and and div for infinity loading. But after re-render infinity loading my "useObserver" hook doesn't work.

My "useObserver" hook:

import { useEffect, useRef } from "react";

export const useObserver = (ref, canLoad, isLoading, callBack) => {

const observer = useRef();

useEffect(() => {
    if (isLoading) return;
    if (ref.current === undefined || ref.current === null) return;
    if (observer === null) return;
    if (observer.current) observer.current.disconnect();

    var callBackObserver = (entries) => {
        if (entries[0].isIntersecting && canLoad) {
            callBack();
        }
    };

    observer.current = new IntersectionObserver(callBackObserver);
    observer.current.observe(ref.current);
}, [isLoading]);
};

My pagination switcher component:

import React from 'react';
import PostList from './PostList';
import Loader from './UI/loader/Loader';
import Pagination from './UI/pagination/Pagination';

export default function PaginationType({ isPagination, isPostLoading, removePost,
 sortedAndSearchedPosts, title, page,
 changePage, totalPages, lastElement }) {

 if (isPagination) {
    return (
        <div>
            {isPostLoading
                ? <div style={{ display: 'flex', justifyContent: 'center', marginTop: 50 }}><Loader /></div>
                : <PostList
                    remove={removePost}
                    posts={sortedAndSearchedPosts}
                    title={title}
                />
            }

            <Pagination page={page}
                changePage={changePage}
                totalPages={totalPages}
            />
        </div>
    );
}
else {
    return (
        <div>
            {isPostLoading &&
                <div style={{ display: 'flex', justifyContent: 'center', marginTop: 50 }}><Loader /></div>
            }

            <PostList
                remove={removePost}
                posts={sortedAndSearchedPosts}
                title={title}
            />
            <div ref={lastElement} style={{ height: 20, background: 'red' }} />
        </div>
    );
}
};

Code from component that calling pagination switcher:

function Posts() {

 const [isClassicPage, setClassicPage] = useState(true);
 const [page, setPage] = useState(1);
 const [posts, setPosts] = useState([]);
 const [totalPages, setTotalPages] = useState(0);

 const [fetchPosts, isPostLoading, postError] = useFetching(async (limit, page) => {
 const response = await PostService.getAll(limit, page);
 if (isClassicPage) {
   setPosts(response.data);
 }
 else {
   setPosts([...posts, ...response.data]);
 }
 const totalCount = response.headers['x-total-count'];
 setTotalPages(getPageCount(totalCount, limit));
 });

 const lastElement = useRef();  

 useObserver(lastElement, page < totalPages, isPostLoading, () => {
   setPage(page + 1);
 });

 return (
  <div className="App">

  <PaginationSwitcher setClassicPage={setClassicPage} />      

  {postError &&
    <h1>Load error, so sorry :C</h1>
  }

  <PaginationType
    isPagination={isClassicPage}
    isPostLoading={isPostLoading}
    removePost={removePost}
    sortedAndSearchedPosts={sortedAndSearchedPosts}
    title={"List of Posts 1"}
    page={page}
    changePage={changePage}
    totalPages={totalPages}
    lastElement={lastElement}
  />

</div>
);
}
export default Posts;

I expecting that after switching between two buttons and re-rendering components all will be work fine!

Cannot read properties of null (reading 'map') in React

I was trying to have my search bar display some results but it did not and is showing the error

Cannot read properties of null (reading 'map')
// import axios from "axios";
import React, { useEffect, useState } from "react";
import lodu from "../../utils/lodu"
import { Link } from "react-router-dom";
function Topnav() {
    const [query, setquery] = useState("");
    const [searches, setsearches] = useState(null);
    const getSearches = async () => {
        try {
            const { data } = await lodu.get(`/search/multi?query=${query}`);
            setsearches(data.results)
        } catch (error) {
            console.log("error is ", error)
        }
    }
    useEffect(() => {
        getSearches();
    }, [query])
    return (
        <>
            <div className="w-full h-[12vh] relative flex justify-center items-center">
                <i class="text-zinc-400 text-3xl ri-search-2-line"></i>
                <input onChange={(e) => { setquery(e.target.value) }} value={query} className="w-[50%] text-zinc-200 mx-10 p-3 text-xl outline-none bg-transparent border-none" type="text" placeholder="search anything?" />
                {query.length > 0 && (<i
                    onClick={() => setquery("")}
                    class="text-zinc-400 text-3xl ri-xrp-fill"></i>)}
                <div className="w-[50%] absolute max-h-[50vh] bg-zinc-200 top-[90%] overflow-auto">
                    {searches.map((s, i) => (
                        <Link key={i}
                            className="hover:text-zinc-100 hover:bg-zinc-400 duration-200 font-semibold w-[100%] flex justify-start items-center p-8 bg-zinc-200 border-b-2">
                            <img src="" alt="" />
                            <span>hi</span>
                        </Link>
                    )
                    )}


                </div>
            </div>

        </>)
}

export default Topnav

Component only has access to array's old state

I'm working with React and I have a table that users can add and delete rows from. The table is made with an array of components. Each component/row has a trash can icon that when clicked executes the delete row function. It would seem that each component only has access to the old state of the array/table, and so deleting doesn't work correctly. Any ideas how I could fix this issue?

An example of a component in the useState array that makes up this table:

<Row
  className={className}
  columns={columns}
  text={text}
  key={key}
  keyProp={key}
  deleteFunction={() => removeRow(key)}
/>

The delete function that is a prop for every row/component in the array:

function removeRow(key) {
  setMeals(meals.filter(i => i.props.keyProp !== key));
  // This should only remove the one row which had its trash can icon clicked.
  // If there's 10 rows and you click the trash can for row 4, rows 4-10
  // will be deleted.
  // If you click the trash can for row 7, rows 7-10 will be deleted and so on.
}

react-horizontal-scrolling-menu scrolling error

**Hello, I'm having a problem with react-horizontal-scrolling-menu , when scrolling, it scrolls to the right a lot, and the rest of the elements disappear, and when you add overflowX: 'scroll' to the BOX, the scroll doesn't work until after the first click

Plus LeftArrow, RightArrow don't work

Take a look at the code**

[error img here]
1

<Box component="div" sx={{position:'relative', width:'100%',p:'20px'}}>
        <HorizontalScrollbar data={bodyParts} bodyParts={bodyParts} bodyPart={bodyPart} setBodyPart={setBodyPart}/>
  </Box>

HorizontalScrollba

  import React, { useContext } from 'react';
import { ScrollMenu, VisibilityContext } from 'react-horizontal-scrolling-menu';
import { Box, Typography } from '@mui/material';
import BodyPart from './BodyPart';
import RightArrowIcon from '../assets/icons/right-arrow.png';
import LeftArrowIcon from '../assets/icons/left-arrow.png';

const LeftArrow = () => {
  const { scrollPrev } = useContext(VisibilityContext);

  return (
    <Typography onClick={() => scrollPrev()} className="right-arrow">
      <img src={LeftArrowIcon} alt="right-arrow" />
    </Typography>
  );
};

const RightArrow = () => {
  const { scrollNext } = useContext(VisibilityContext);

  return (
    <Typography onClick={() => scrollNext()} className="left-arrow" >
      <img src={RightArrowIcon} alt="right-arrow"/>
    </Typography>
  );
};

const HorizontalScrollbar = ({ data, bodyParts, setBodyPart, bodyPart }) => (
  <Box mt={4} sx={{position:'static'}}>
  <ScrollMenu LeftArrow={LeftArrow} RightArrow={RightArrow}>
    {data.map((item) => (
      <Box
        key={item.id || item}
        itemId={item.id || item}
        title={item.id || item}
        m="0 40px"
      >
         <BodyPart item={item} setBodyPart={setBodyPart} bodyPart={bodyPart} /> 
      </Box>
    ))}
  </ScrollMenu>
  </Box>
);

export default HorizontalScrollbar;

react-router-dom is not working for nested page and sub-pages for react application in sub-directory

I am working on react application using vite and I am using latest version of react-router-dom v 6.23.0. My react application is build on the subdirectory (./new-mobile/dist) of main directory.

Here is my main.tsx file

import ReactDOM from 'react-dom/client'
import App from './App'
import './index.css'
import store from '../redux/store.js'
import { Provider } from 'react-redux'
import {RouterProvider, createBrowserRouter} from 'react-router-dom';
import App3 from './App3'
import TestFile from './TestFile'

const basename = '/new-mobile/dist';

const router = createBrowserRouter([
  {
    path: '/',
    element: <App />,
    children: [
      {
        path: 'testfile',
        element: <TestFile />
      }
    ]
  },
  {
    path: 'app3',
    element: <App3 />
  }
],
{
  basename: basename
});

ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(
  <Provider store={store}>
    <RouterProvider router={router} />
  </Provider>
);

And here is the vite.config.ts file

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import Checker from 'vite-plugin-checker';

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    react(),
    Checker({ typescript: true }),
  ],
  base: './new-mobile/dist'
})

The main problem is when i am going on home page https://my-domain/new-mobile/dist it it working correctly, but when I go to its nested page (https://my-domain/new-mobile/dist/testfile) or child/sub-page like (https://my-domain/new-mobile/dist/app3) it breaks outs.

Also, this router is working fine on my local setup but breaks on test environment.

Things I tried: I tried adding basename but is is also not working. I tried jsx version of router, but still not working.

when I try to access /app3, this comes. broser image

How to change the size of a Shadcn dialog component?

I have a dialog component from shadcn which contains something that is wider than the actual dialog. I have been trying to apply tailwind styles such as w-[full] to the but that seemed to not do anything. Is there a way to change the size of the actual dialog that pops up? I will paste my code. Thanks!

Shadcn - https://ui.shadcn.com/docs/components/dialog

Here is a photo of my design. Design

'use client';

import React, { useState } from 'react';
import CollapseCardFeatures from './_components/Cards';
import Quizmodal from './_components/QuizModal';

import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog"

const Page: React.FC = () => {

  return (
    <div className='w-full h-full relative'>
      <CollapseCardFeatures />
      <section className='w-full h-full flex justify-center py-5'>
        <Dialog>
            <DialogTrigger asChild>
                <div className="group relative w-fit transition-transform duration-300 active:scale-95">
                <button className="relative z-10 rounded-lg bg-gradient-to-br from-indigo-500 to-fuchsia-500 p-0.5 duration-300 group-hover:scale-110">
                    <span className="block rounded-md bg-slate-950 px-4 py-2 font-semibold text-slate-100 duration-300 group-hover:bg-slate-950/50 group-hover:text-slate-50 group-active:bg-slate-950/80">
                    Take Quiz
                    </span>
                </button>
                <span className="pointer-events-none absolute -inset-4 z-0 transform-gpu rounded-2xl bg-gradient-to-br from-indigo-500 to-fuchsia-500 opacity-30 blur-xl transition-all duration-300 group-hover:opacity-90 group-active:opacity-50" />
                </div>
            </DialogTrigger>
            <DialogContent className="w-full">
                <Quizmodal />
            </DialogContent>
        </Dialog>
        </section>
    </div>
  );
}

export default Page;


How do I make a html element draggable while not triggering its onClick?

I have to make a chat widget movable. This chat widget is injected by an external script (SFDC Embedded Service, to be specific). Hence, I do not have access to the click handlers of the chat widget.

I am currently using event handlers of the embedded service to attach 'mousedown', 'mouseup' and 'mousemove' event listeners to the chat widget to make it movable.

While the widget is movable by dragging, upon mouseup, the mouseclick event is also triggered and the chat gets activated.

Can I avoid triggering the mouseclick event given the external nature of the widget?

I am also using react if that matters.

The chat widget is also attached directly onto the document body by the salesforce script, so a container is out of the question.

HTML:

<body>
    <script async src='salesforce.com/esw.min.js' /> // external script that adds chat widget
</body>

rough representation of esw.min.js:

const chatWidget = <chat-widget />
chatWidget.addEventListener('click', openChat)
document.querySelector('body').append(chatWidget) // adds chat widget into body

my code:

const widgetObserver = new MutationObserver((mutations, observer) => {
    const helpButton = document.querySelector('chat-widget');

    if (helpButton) {
        !helpButton.draggable && enableDragging(helpButton);
        observer.disconnect();
    }
});

function enableDragging(element) {
    var displacedX = 0,
        displacedY = 0,
        currentX = 0,
        currentY = 0;
    // otherwise, move the DIV from anywhere inside the DIV:
    element.onmousedown = dragMouseDown;
    element.style.right = currentX + 'px';
    element.style.bottom = currentY + 'px';
    element.draggable = true;
    function dragMouseDown(e) {
        e = e || window.event;
        e.preventDefault();
        // get the mouse cursor position at startup:
        currentX = e.clientX;
        currentY = e.clientY;
        document.onmouseup = closeDragElement;
        // call a function whenever the cursor moves:
        document.onmousemove = elementDrag;
    }

    function elementDrag(e) {
        e.preventDefault();
        // calculate the new cursor position:
        displacedX = currentX - e.clientX;
        displacedY = currentY - e.clientY;
        currentX = e.clientX;
        currentY = e.clientY;
        // set the element's new position:
        element.style.top = element.offsetTop - displacedY + 'px';
        element.style.left = element.offsetLeft - displacedX + 'px';
}

    function closeDragElement() {
        // stop moving when mouse button is released:
        document.onmouseup = null;
        document.onmousemove = null;
    }
}

NextJS Image component with fixed witdth and auto height

I am using NextJS Image component. I want the image to fill 100% width and take as much height as it needs to maintain the aspect ratio. I have tried many different variations of this code but it will not work unless I define a fixed height on the parent div.

export default function PhotoCard({ img }: Props) {
      return (
        <div className="relative w-full h-32 my-2">
          <Image alt={img.title} src={img.url} layout="fill" objectFit="cover" />
        </div>
      );
    }

This is the current behaviour images in app

How can I fix this error in my react-native app with popups, useState and Pressables

My project has been halted a couple hours because the pressables aren't doing anything! (This is react native project) I can't seem to find a solution because everytime I am close to finding one they just cause more errors. Hopefully yall can help me. Thanks.

Heres profile.js

import { View, Text, StyleSheet, Pressable } from "react-native";
import PopUp from "./PopUp.js"
import Box from "./Box";
import { useState } from "react";

const ProfileScreen = () => {
   const [visible, setVisible] = useState()

  function PopUpScreen() {
    visible = styles.popup.display
    setVisible(prevVisible => !prevVisible);
  }

  return (
    <View style={styles.container}>
       <Text style={styles.text}>SIGNUP</Text>
      <Pressable style={styles.button} onPress={PopUpScreen}>
        <Text onPress={PopUpScreen} style={styles.text2}>๐Ÿ””</Text>
        <Text onPress={PopUpScreen} style={styles.text4}>๐Ÿ”ด</Text>
        <Text onPress={PopUpScreen} style={styles.text3}>3</Text>
      </Pressable>
      <PopUp style={styles.popup}>
        <Box></Box>
        <Box></Box>
        <Box></Box>
        <Box></Box>
        <Box></Box>
      </PopUp>


    </View>

  );
};



export default ProfileScreen;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: "center",
    justifyContent: "center",

  },
  text: {
    fontSize: 24,
    fontWeight: "bold",
    marginBottom: 16,
  },
  text3: {
    fontSize: 20,
    fontWeight: "bold",
    position: 'absolute',
    top: 15,
    right: 44,

  },
  text2: {
    fontSize: 24,
    fontWeight: "bold",
    position: 'absolute',
    top: 20,
    right: 30,
  },
  text4: {
    fontSize: 20,
    fontWeight: "bold",
    position: 'absolute',
    top: 15,
    right: 37,
  },
  button: {
    fontSize: 20,
    fontWeight: "bold",
    position: 'absolute',
    top: 15,
    right: 40,
  },
  popup: {
    backgroundColor: "#C0C0C0",
    padding: 20,
    width: 300,
    height: 400,
    borderWidth: 1,
    borderStyle: "solid",
    borderColor: "black",
    margin: 2,
    elevation: 5,
    position: "absolute",
    zIndex: 1,
    fontSize: 24,
    display: "none"
  },
  text5: {
    fontSize: 24,
    textAlign: "center",
    alignSelf: "center",
    fontWeight: "bold",
    marginBottom: 16,
  },
});

This is box

import { View, Text, StyleSheet } from "react-native";

export default function Box({ children, style }) {
  return (
    <View style={[styles.box, style]}>
      <Text style={styles.text}>{children}</Text>
      <Text style={styles.text3}>โžค</Text>
    </View>
  );
}


const styles = StyleSheet.create({
  box: {
    backgroundColor: "#C0C0C0",
    padding: 20,
    width: 350,
    borderWidth: 1,
    borderStyle: "solid",
    borderColor: "black",
    margin: 2
  },
  text: {
    fontSize: 24,
    fontWeight: "bold",
    textAlign: "left",
    color: "white",
  },
  text3: {
    fontSize: 24,
    fontWeight: "bold",
    textAlign: "right",
    color: "white",
  },
});

This is popup

import { View, Text, StyleSheet } from "react-native";

export default function PopUp({ children, style }) {
    return (
      <View style={[styles.box, style]}>
        <Text style={styles.text}>{children}</Text>
      </View>
    );
  }

const styles = StyleSheet.create({
    box: {
      backgroundColor: "#C0C0C0",
      padding: 20,
      width: 350,
      borderWidth: 1,
      borderStyle: "solid",
      borderColor: "black",
      margin: 2
    },
})

This is app.js

import { NavigationContainer } from "@react-navigation/native";
import { createBottomTabNavigator } from "@react-navigation/bottom-tabs";
import SettingsScreen from "./screens/SettingsScreen";
import CourseListScreen from "./screens/CourseList";
import ProfileScreen from "./screens/Profile";
import Ionicons from "@expo/vector-icons/Ionicons";
import { AboutStack } from "./AppStack";

const Tab = createBottomTabNavigator();

export default function App() {
  return (
    <NavigationContainer>
      <Tab.Navigator
        screenOptions={{
          //   tabBarShowLabel: false,
          tabBarLabelPosition: "below-icon",
          tabBarActiveTintColor: "purple",
        }}
      >
        <Tab.Screen name="Course List" component={CourseListScreen} />
        <Tab.Screen
          name="Profile"
          component={ProfileScreen}
          options={{
            tabBarLabel: "My Profile",
            tabBarIcon: () => <Ionicons name={"person"} size={20} />,
            tabBarBadge: 3,
          }}
        />
        <Tab.Screen name="Settings" component={SettingsScreen} />
        <Tab.Screen
          name="About Stack"
          component={AboutStack}
          options={{
            headerShown: false,
          }}
        />
      </Tab.Navigator>
    </NavigationContainer>
  );
}

Gettig error on installing the Phonepe in React native

I am trying to integrate the Phonepe in react native application by using below command.

npm iย https://phonepe.mycloudrepo.io/public/repositories/phonepe-mobile-react-native- sdk/releases/v2/react-native-phonepe-pg.tgz

Above command i got from Phonepe payment gateway integration website.https://developer.phonepe.com/v1/docs/react-native-sdk-integration-standard

But i am getting below error.Please guided me how we can integrate the Phone pe.

 Unknown command: "i https://phonepe.mycloudrepo.io/public/repositories/phonepe-mobile-react- native-sdk/releases/v2/react-native-phonepe-pg.tgz"

Trying to integrate Phonepe Payment gateway

object data push using map function in react/javscript

object array

{ 
 first : { label :"a" , status : true , text: "dummy" },
 second : { label :"b" , status : true , text: "dummy" },
 third : { label :"c" , status : false , text: "dummy" }
 }

I have the object and map and push inot other object check the object key have label is "c" ,if present then dont push

 const newData = data && data.map(item => {
            if(item.label !=='c') {   
                return {
                ...item, 
                };
            }
            }); 

expected result

{ 
 first : { label :"a" , status : true , text: "dummy" },
 second : { label :"b" , status : true , text: "dummy" } 
 }

Uncaught TypeError: Object prototype may only be an Object or null: undefined when install vite

I've changed react-script and installed vite and I have an issue that it show white page

inherits_browser.js:5 Uncaught TypeError: Object prototype may only be an Object or null: undefined
at Function.create (<anonymous>)
at Object.inherits (inherits_browser.js:5:29)
at node_modules/jws/lib/data-stream.js (data-stream.js:39:6)
at __require2 (chunk-WGAPYIUP.js?v=4dc5655b:19:50)
at node_modules/jws/lib/sign-stream.js (sign-stream.js:3:18)
at __require2 (chunk-WGAPYIUP.js?v=4dc5655b:19:50)
at node_modules/jws/index.js (index.js:2:18)
at __require2 (chunk-WGAPYIUP.js?v=4dc5655b:19:50)
at node_modules/jsonwebtoken/decode.js (decode.js:1:11)
at __require2 (chunk-WGAPYIUP.js?v=4dc5655b:19:50)

enter image description here

module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
ctor.prototype = Object.create(superCtor.prototype, {
  constructor: {
    value: ctor,
    enumerable: false,
    writable: true,
    configurable: true
  }
});

enter image description here

I don't know that it's error. Please help me to check this issue

I want to run my project

Cannot read properties of undefined (reading 'choices') in React application using OpenAI API

Edit: Issue was solved

I'm working on a React application where I'm using the OpenAI API to communicate with the AI. In my application, I'm trying to send user input to the API and receive a response from the AI. However, I'm encountering the following error:

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'choices')
    at sendMsgToOpenAI (openai.js:15:1)
    at async handleSend

Here's the relevant portion of my code:

App component (App.js)

import './App.css';
import AIlogo from './assets/chatgpt.svg';
import addBtn from './assets/add-30.png';
import msgIcon from './assets/message.svg';
import home from './assets/home.svg';
import saved from './assets/bookmark.svg';
import upgrade from './assets/rocket.svg';
import sendBtn from './assets/send.svg';
import userIcon from './assets/user.svg';
import AIchat from './assets/chatgptLogo.svg';
import { sendMsgToOpenAI } from './openai';
import { useState } from 'react';

function App() {

  const[input, setInput] = useState("");

const handleSend = async() => {

  const res = await sendMsgToOpenAI(input);
  console.log(res);
}

  return (
    <div className="App">
      <div className ="sideBar">
     <div className ="upperSide">
     
     <div className ="upperSideTop"><img src={AIlogo} alt="Logo" className="logo"/><span className="brand">Eclipse AI</span>  
     <button className="midBtn"><img src={addBtn} alt="" className="addBtn" />New Chat</button>
      
     <div className="upprtSideBottom">
      
    <button className="query"><img src={msgIcon} alt=""/> What is Programming ?</button>
    <button className="query"><img src={msgIcon} alt=""/> How to use an API ?</button>
    </div>
     </div>
     </div>


   
        
       <div className ="lowerSide">
       <div className ="listItems"><img src={home} alt="" className="listitemsImg" />Home</div>
       <div className ="listItems"><img src={saved} alt="" className="listitemsImg" />Saved</div>
       <div className ="listItems"><img src={upgrade} alt="" className="listitemsImg" />Upgrade to Pro</div>
       </div>
     </div>

     <div className ="main">
<div className="chats">

<div className="chat">
 <img src={AIchat} alt=""/><p className="txt">uncountable noun [usu with supp] You can use stuff to refer to things such as a substance, a collection of things, events, or ideas, or the contents of something in a general way without mentioning the thing itself by name.</p>
 <img src={userIcon} alt=""/><p className="txt">uncountable noun [usu with supp] You can use stuff to refer to things such as a substance, a collection of things, events, or ideas, or the contents of something in a general way without mentioning the thing itself by name.</p>
</div>
</div>
 



<div className="chatFooter">
  <div className="inp">
    <input type="text" placeholder='Message EclipseAI' value={input} onChange={(e)=>{setInput(e.target.value)}} /><button className="send" onClick={handleSend}><img src={sendBtn} alt="send-icon" /></button>

  </div>
  <p>This page of EclipseAI is still under development, including the user interface.</p>
</div>
     </div>
    </div>
  );
}

export default App;

OpenAI function (openai.js):

const OpenAI = require('openai');

const openai = new OpenAI({ apiKey: 'Key in here', dangerouslyAllowBrowser: true });

export async function sendMsgToOpenAI(message) {
    const res = await openai.completions.create({
        model: 'gpt-3.5-turbo-instruct',
        prompt: message,
        temperature: 0.7,
        max_tokens: 256,
        top_p: 1,
        frequency_penalty: 0,
        presence_penalty: 0
    });
    return res.data.choices[0].text;
}

The error occurs when I try to call the sendMsgToOpenAI function. Specifically, it happens when trying to access res.data.choices[0].text.

What I've tried:

Checked that the API key is correct and authorized for the model I'm using. Verified that I'm using the correct API endpoint.

Additional Information:

I'm using gpt-3.5-turbo-instruct as the model.

I was following a YouTube tutorial to set up this application, Link to tutorial: https://www.youtube.com/watch?v=EzkWAviyYgg&t=392s&ab_channel=GreatStack

Has anyone else encountered this error or know how to resolve it? Any help would be appreciated.

Solution:

Replacing return res.data.choices[0].text With return res.choices[0].text

disable button on error multiple times in react js

I am trying to disable a button based on validation error on click. if any change on the form input field the button should be enabled, till here is working for me. but when I click next if I get error again the button should get disabled but can't seem to achieve it. So, works fine first-time button click but does not work second time since authFailed has error. can someone please help me to solve this problem?

**Below are the conditions I am using :** 
let disableButton=false;
let existingError=false;
    
const authFailed=hasError(AUTH_FAILED);
    
if (authFailed && !existingError) {
   disableButton=true;
} else {
   disableButton=false;
}
if (authFailed) {
   existingError=true;
}
    
**Input Field:**
<Input fieldName="Name" value={value} onChange={()=>{disableButton=false;}} />
    
**Button:**
<button onClick={() => {
    existingError = false;
    onButton();
  }}`enter code here`
  disabled={disableButton}
  isLoading={false}
/>

How to Delay a Fetch Request in JavaScript Without Using setTimeout or setInterval?

I'm working on a JavaScript project where I need to delay a fetch request. However, due to some project constraints, I can't use setTimeout or setInterval. I'm aware that these are the usual methods for delaying execution in JavaScript, but I need an alternative approach because these functions have been overridden in our codebase.

I've considered using Promise or busy-waiting with a while loop, but these methods are not ideal as they either still use setTimeout under the hood or block the execution of other code.

Here's a basic example of the kind of operation I'm trying to perform:

async function delayedFetch(url, delayTime) {
  // Need to delay here without using setTimeout or setInterval
  const response = await fetch(url);
  const data = await response.json();
  return data;
}

delayedFetch('https://api.example.com/data', 2000)
  .then(data => console.log(data));

How i can get data from post request?

I have linked my website to a payment gateway, and when the payment process is completed successfully, the payment gateway will transfer me to my website via a post request with the data of the completed transaction. Question: How can I obtain this data to perform some operations on the site, knowing that I use react.js

i try get data from post request

Accessing child of object - React JavaScript

import React from "react";

const VideoDetails = ({ info }) => {
  const { snippet, statistics } = info;
  console.log(snippet);
  return (
    <div>
      <h1>{snippet.title}</h1>
    </div>
  );
};

export default VideoDetails;

Hi everyone, I have pasted the code in which I'm facing the issue. Here I can easily console.log the "snippet and statistics", which are children of info props. But there are children in the "snippet" too. When I'm trying to access the child of "snippet/statistics", I'm getting the value for the first run of code. When I'm refreshing the page then I'm facing an error as shown.When refreshing the page

I'm not able to understand if I can log "snippet" then why can't I use the children present in "snippet".

โŒ
โŒ