Can’t fetch online users

I’m developing a MERN chat application and I can’t fetch all the avaliable users in the frontend.

Read before answering:

  1. To fetch all avaliable users, you must login.
  2. Authentication uses JWT and the JWT Token is stored in the cookies tab in the browser
  3. Login in the frontend is done using RTK Query

Here’s the code:

JWT method:

UserSchema.methods.getJwtToken = function(){
  return jwt.sign({ id: this._id }, process.env.JWT_SECRET, {
    expiresIn: process.env.JWT_EXPIRES_TIME
  });
}

JWT Creation:

export default (user, statusCode, res) =>{
  const token = user.getJwtToken(); // Create JWT Token

  const options ={
    expires: new Date(Date.now() + process.env.COOKIE_EXPIRATION_TIME * 24 * 60 * 60 * 1000)
  }
  res.status(statusCode)
  .cookie("token", token, options)
  .json({ user, token });
}

User Authentication (Backend):

import asyncHandler from "express-async-handler";
import jwt from "jsonwebtoken";

import User from "path/to/userModel";
import ErrorHandler from "path/to/errorHandler";

export const isAuthenticatedUser = asyncHandler(async (req, res, next) =>{
  const { token } = req.cookies

  if(!token){
    return next(new ErrorHandler("Login to gain access to this resource", 401));
  }
  const decoded = jwt.verify(token, process.env.JWT_SECRET); // Verify the user's token
  req.user = await User.findById(decoded.id);
  next();
});
`

Fetching Users (Frontend):

// Imports

const Users = () =>{
  const [users, setUsers] = useState([]);

  const { refresh, setRefresh } = useContext(chatContext);

  const dispatch = useDispatch();

  const theme = useSelector((state) => state.theme);
  const { user } = useSelector((state) => state.user);

  useEffect(() =>{
    console.log("Users Refreshed");
    const config ={
      headers: { Authorization: `Bearer ${user?.data?.token}` },
    };
    console.log(config)
    axios.get("http://localhost:5001/api/v1/fetchusers", config).then((data) => {
      console.log("User Data Refreshed");
      setUsers(data);
    });
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [refresh]);

  const iconHandler = (e) =>{
    e.preventDefault();
  }

  return(
    <>
      <MetaData title={"Users"}/>
      <div className="list-container d-flex flex-column">
        <div className={`usersgroups-header d-flex align-items-center bg-light ${theme ? "" : "dark"}`}>
          <img src={user?.picture?.url} alt={user?.name} style={{ height: "2rem", width: "2rem", borderRadius: "20px" }}/>
          <p className="usersgroups-title fw-bolder mt-3">Online Users</p>
          <Button className="border-0 bg-transparent" style={{ color: "black" }}
          onClick={() =>{ setRefresh(!refresh); }}>
            <MdOutlineRefresh onClick={iconHandler} className={`icon ${theme ? "" : "dark"}`}/>
          </Button>
        </div>

        <div className={`sb-search d-flex align-items-center bg-light ${theme ? "" : "dark"}`}>
          <BsSearch onClick={iconHandler} className={`icon mx-1 my-2 ${theme ? "" : "dark"}`}/>
          <input type="search" placeholder="Search" className={`search-box border-0 w-100 ${theme ? "" : "dark"}`}/>
        </div>

        <div className="usersgroups-list flex-fill overflow-scroll">
          {users.map((user, index) =>{
            return(
              <motion.div
              className={`d-flex align-items-center ${theme ? "list-tem" : "dark-list-tem"}`}
              whileHover={{ scale: 1.01 }}
              whileTap={{ scale: 0.98 }}
              key={index}
              onClick={() =>{
                console.log("Creating chat with ", user.name);
                const config ={
                  headers: {Authorization: `Bearer ${user.data.token}` },
                };
                axios.post("http://localhost:5001/api/v1/chat/",{
                  userID: user._id
                },config);
                dispatch(refreshSidebarFun())}}>
                <p className=
                {`con-icon d-flex justify-content-center align-items-center bg-${theme ? "dark" : "light"} text-${theme ? "light" : "dark"} mt-3`}>T</p>
                <p className={`con-title fw-bold mt-3 text-${theme ? "dark" : "light"}`}>Test User</p>
              </motion.div>
            )
          })}
        </div>
      </div>
    </>
  )
}

export default Users;

Your help will be appreciated

I have a single horizontal bar chart in chartjs. I want the datasets to have different sizes but not be centered, they always start on the same axis?

const config = {
        type: 'bar',
        plugins: [ChartDataLabels],
        data,
        options: {
          indexAxis: 'y',
          aspectRatio: 7,
          scales: {
            x: {
              tooltipFormat: 'HH:mm',
              type: 'time',
              time: {
                unit: 'hour',
                displayFormats: {
                  hour: 'HH:mm'
                },

              },
              min: '00:00',
              max: '24:00',
              grid: {
                display: false,
                drawBorder: true,
                drawTicks: true,
                borderColor: 'white'
              },
              ticks: {
                display: true
              },

            },
            y: {
              beginAtZero: true,
              stacked: true,
              grid: {

                display: false,
                drawBorder: false,
                drawTicks: false,
                borderColor: 'white'
              },
              ticks: {
                display: false
              },
            },
          },

          plugins: {

            tooltip: {
              callbacks: {
                title: context => {

                  const d = new Date(context[0].parsed._custom.start);
                  const e = new Date(context[0].parsed._custom.end);
                  const startHours = d.toLocaleString([], {
                    hour: "2-digit",
                    minute: "2-digit"
                  });
                  const endHours = e.toLocaleString([], {
                    hour: "2-digit",
                    minute: "2-digit"
                  });

                  if (context[0].dataset.label === 'PAISES') {
                    return (context[0].raw.entryType + ": " + startHours);
                  }
                  else if (context[0].dataset.label === 'VEICULOS') {
                    return "DAS " + startHours + " ÀS " + endHours + "n" + context[0].raw.kms;
                  }
                  else {
                    return context[0].dataset.label + "n" + "DAS " + startHours + " ÀS " + endHours;
                  }
                },
                label: context => {
                  return "";
                },
              }
            },

            datalabels: {
              anchor: 'center',
              align: 'bottom',
              labels: {
                value: {
                  color: 'blue'
                }
              }
            },

            zoom: {

              zoom: {
                drag: {
                  enabled: true,
                },

              },

              wheel: {
                enabled: true,
                modifierKey: 'ctrl'

              },

              mode: 'xy', scaleMode: 'x',


            },
            autocolors: false,
            legend: {
              display: false
            },
          }
        },
      }; 

in this case the rest dataset (blue) had to come down instead of being centered. I don’t know if I need to add any configuration. If I set barpercentage or categorypercentage or barthickness it never stays aligned at the bottom. always at the center

image here

Shopping cart is not getting updated and there is “undefined” pop up message when trying to add new item to cart

Shopping cart is not getting updated and there is “undefined” pop up message when trying to add new item to cart.

Tried every solution that I found on the internet – reset theme, reset shopping cart module, updating every module there is, updating jquery, nothing seems to fix my problem. Pop up looks like this: popup. There is also a jquery warning that looks like this, but I don’t understand it fully: jquery warning Prestashop version 1.7

Jest – Can’t find module Error for split-pane-react

I am trying to test my component with [email protected] with Jest in a Next.js project with typescript.

I am receiving the error as :
Cannot find module ‘split-pane-react’ from ‘my component path’
on running the test case.

I have tried adding the path in moduleNameMapper in jest.config.js as
'split-pane-react': '<rootDir>/node_modules/split-pane-react/esm/index.js'
but it is giving an error of export like this

({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){export * from './SplitPane';
                                                                                      ^^^^^^
SyntaxError: Unexpected token 'export'

I have also tried transformIgnorePatterns for the export issue but that also doesn’t work.

Package versions:
“react”: “18.2.0”,
“next”: “12.3.4”,
“jest”: “29.7.0”,
“ts-jest”: “29.1.1”,
“ts-node”: “10.9.1”,

ServiceWorker deleting cache during install event

Is it safe to delete all cache during the install event instead of during activate event ?

My problem is that my service worker deployed, keep caching old file from previous cache because I forgot to set Cache-control header to “no-cache”. So it keep serving not up-to-date app. My idea is to delete all cache as soon as the service worker install, then cache the lastest files.

It seams to work on my development environment, but I wonder if it is good practice.

self.addEventListener('install', evt => {
    evt.waitUntil(
        // first delete all caches
        caches.keys().then(keys => {
            console.log('deleting all cache');
            return Promise.all(keys
                .map(key => caches.delete(key))
            )
        }).then(res => {
            // then cache files
            caches.open(staticCacheName).then((cache) => {
                console.log('caching shell assets');
                cache.addAll(assets);
            })
        })
    )
});


// activate event
self.addEventListener('activate', evt => {
    // evt.waitUntil(
    //     caches.keys().then(keys => {
    //         return Promise.all(keys
    //             .filter(key => key !== staticCacheName)
    //             .map(key => caches.delete(key))
    //         )
    //     })
    // )
});```

I will trying to add the keycloack but I am faceing the some issue [closed]

***I will trying to add the keycloack auth but I am facing the some error in this code.KeycloakUserService is no any issue but I am not able to implemented the keycloak ***
import KeycloakUserService from “./components/Login/KeycloakUserService”;

initializeIcons();

const router = createHashRouter([
    {
        path: "/",
        element: <Layout />,
        children: [
            {
                index: true,
                element: <Chat />
            },
            {
                path: "qa",
                lazy: () => import("./pages/oneshot/OneShot")
            },
            {
                path: "*",
                lazy: () => import("./pages/NoPage")
            }
        ]
    }
]);
ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
    <React.StrictMode>
        <RouterProvider router={router} />
    </React.StrictMode>
    
);

KeycloakUserService.initKeycloak(router);

React useCallback/useEffect deps object property usage

Is it correct to include in useEffect/useCallback deps only used props, but not whole object?

For example:

function Component (props) {
  useEffect(() => console.log(props.someValue), [props.someValue]) // ? eslint plugin tells that you should include props, not props.someValue.
  return someVal
}

API Authentication with active Session

Currently I am trying to trigger an Event within MicroStrategy.
Unfortunately the Webinterface does not support that but the API does and the Enduser can‘t use any other MicroStrategy Tool.

So my solution to that Problem would be to call the API via JavaScript inside a HTML container of a Dossier.
The Problem is that i can‘t authenticate myself without having my password in clear text what is a no go to me.

The thing is, the API Playground is automatically authenticated if you are logged in, so one of my questions is how does the playground authenticate itself?

And with the GET Token method your are able to connect via existing cookies. I can find those in my browser but the one needed (Session ID) is html only so I can‘t read nor pass it further.

Is there a way to connect without other MicroStrategy Tools or having to save your password somewhere?

Expanding Retrieved Data from LinkedIn at First Login

In our web application using the LinkedIn API, we currently fetch only basic user information (name and email) at login. We aim to extend this to include more detailed profile data such as work experiences, education, and skills during the initial login.

Our integration is presently limited to basic data retrieval. We haven’t yet implemented functionality for fetching extended profile information at the first login.

I am looking for advice on modifying our API calls or authentication process to access a broader set of user data right at the initial login. Insights on specific API endpoints, required permissions, or other technical considerations would be greatly appreciated.

#linkedin

javascript new and this keyword

I have been given a task at my internship , I have to create math operations like plus(), minus() etc. using this and new keywords.
example:- one().plus().two().equalTo() , given line of code must return 3.

I tried creating functions which returns values.
function one(){ return 1; }.
But I am not able to figureout how plus() and equalto() will work.

Value of the data is not reflecting (React, GraphQL)

I have a Database which has tables with “y” or “n” for yes or no values. I used GraphQL to get the data from the database to my app. My goal was to pass it through a radiogroup so that the it fills the checkbox.

The problem I am facing is that the it is always taking the wrong value.

Here is my code

export function RevOfSymptoms(patientID: any) {
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState(null);
  const [symptoms, setSymptoms] = React.useState<Symptoms | null>(null);
  React.useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await fetch("http://localhost:4000", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            query: `
            query getSymptoms($reviewSympId: ID!) {
              reviewSymp(id: $reviewSympId) {
                p_id
                gq1
                gq2
                gq3
                gq4
                gq5
                gq6
                vascular_dis
                high_col
                heart_dis
                stroke
                high_bp
                eye_surgery
                gluacoma
                amblyopia
                cataract
                retinal_prob
                macular_degen
                strabismus
                lasik
                anemia
                bleeding_dis
                fibromyalgia
                muscular_dys
                osteosrthritis
                fatigue
                fever
                weight_loss
                prostrate_dis
                std
                kidney_dis
                dry_mouth
                hearing_loss
                sinusitis
                dementia
                multiple_sclerosis
                shingles
                migrane
                epilepsy
                depression
                anxiety
                adhd
                tuberculosis
                copd
                asthma
                rosacea
                psoriasis
                eczema
                dia_1
                dia_2
                hormonal_dys
                thyroid_dys
                past_hist
                medications
                allergies
              }
            }
            `,
            variables: {
              reviewSympId: patientID.patientID,
            },
          }),
        });
        const result = await response.json();
        console.log(result);
        if (result.errors) {
          setError(result.errors[0].message);
        } else {
          setSymptoms(result.data.reviewSymp);
        }
      } catch (error: any) {
        setError(error.message);
        console.log(error);
      } finally {
        setLoading(false);
      }
    };
    fetchData();
  }, []);
  
  return (
    <div className="flex flex-row space-x-4">
      <div className="flex flex-col w-1/4 space-y-4">
        {/* General Questions radio card*/}
        <Card>
          <CardHeader>
            <CardTitle className="text-md font-bold mt-">
              General Questions
            </CardTitle>
          </CardHeader>
          <CardContent className="grid md:grid-cols-2 sm:grid-cols-1 gap-1">
            <div className="col-span-1">
              <div className="flex items-center space-x-2">
                <p className="text-sm">Do you sometimes experience dry eyes?</p>
              </div>
            </div>
            <div className="col-span-1">
              <RadioGroup
                defaultValue={symptoms?.gq2 === "y" ? "option-one" : "option-two"}
                className="flex items-center space-x-2 justify-end"
              >
                <div className="flex items-center space-x-2">
                  <RadioGroupItem value="option-one" id="option-one"/>
                  <Label htmlFor="option-one">Yes</Label>
                </div>
                <div className="flex items-center space-x-2">
                  <RadioGroupItem value="option-two" id="option-two"/>
                  <Label htmlFor="option-two">No</Label>
                </div>
              </RadioGroup>
            </div>

I console logged console.log(symptoms?.gq2 === "y" ? "option-one" : "option-two") and noticed this It is showing 2 different Values

My guess is the Radio Group is taking the value before the data is fetched and by default showing option-two and is not getting updated.

How do I resolve this?

Thank you!