upi address decode from scan result

Scanning QR code in react-native using expo-barcodeScanner provided result as below string

let scanResult  = "000201010212021644038463024275060415522024063024275061661000306302427510825HDFC00000010103200000676826530010A0000005240135xyz.63d24732@hdfcbank27380010A000000524012089391981685697707515520454115303356540580.005802IN5919Name Of Merchant 6004PUNE61064110076236052089391981685697707515070863024275630455f3"

How can I decode this to get Upi details like amount, merchant name, Upi Address?

how can I get users from API by department using REACT and REDUX

How can I get the users by deparment from API using React and Redux.

I have got the list of users from API using the AXIOS :

import axios from "axios";
const DEPARTMENTS_GOT_FROM_REST_API = "http://localhost:8082/api/departments";
class AdminSetvice {
    get_all_departments() {
        return axios.get(DEPARTMENTS_GOT_FROM_REST_API)
    }
    get_users_by_depName(depName) {
        return axios.get(DEPARTMENTS_GOT_FROM_REST_API + "/" + depName)
    }
}
export default new AdminSetvice();

For Redux I created

UsersByDep.ActionTypes.js

export default {
    GETTING_USERS_BY_DEPARTMENT: 'GETTING_USERS_BY_DEPARTMENT',
    GET_USERS_BY_DEPARTMENT: 'GET_USERS_BY_DEPARTMENT',
    GET_USERS_BY_DEPARTMENT_ERROR: 'GET_USERS_BY_DEPARTMENT_ERROR',
}

UsersByDep.actions.js

import UsersByDepActionTypes from "./UsersByDep.ActionTypes"

const GettingUsersByDepName = () => ({
    type: UsersByDepActionTypes.GETTING_USERS_BY_DEPARTMENT,
})

const GetUsersByDepName = (users) => ({
    type: UsersByDepActionTypes.GET_USERS_BY_DEPARTMENT,
    payload: users
})
const GettingUsersByDepNameError = (errorMsg) => ({
    type: UsersByDepActionTypes.GET_USERS_BY_DEPARTMENT_ERROR,
    payload: errorMsg,
})



export default {

    GettingUsersByDepName,
    GetUsersByDepName,
    GettingUsersByDepNameError,
}

UsersByDep.InitialState.js

export default {
    usersIsLoading: false,
    users: [],
    usersErrorMessage: null,
}

UsersByDep.Reducer.js

import UsersByDepActionTypes from "./UsersByDep.ActionTypes";
import UsersByDepInitialState from "./UsersByDep.InitialState";


const UsersByDepReducer = (state = UsersByDepInitialState, { type, payload }) => {
    switch (type) {
        case UsersByDepActionTypes.GETTING_USERS_BY_DEPARTMENT:
            return {
                ...state,
                usersIsLoading: true,
            }

        case UsersByDepActionTypes.GET_USERS_BY_DEPARTMENT:
            return {
                ...state,
                usersIsLoading: false,
                users: payload,
            }
        case UsersByDepActionTypes.GET_USERS_BY_DEPARTMENT_ERROR:
            return {
                ...state,
                usersIsLoading: false,
                usersErrorMsg: payload,
            }

        default:
            return state
    }
};

export default UsersByDepReducer;

and UsersByDep.Thunk.js

import UsersByDepService from '../../../Services/Adminservice'
import UsersByDepActions from './UsersByDep.actions'

export const AsyncGetUsersByDepName = (department) => (dispatch) => {
    dispatch(UsersByDepActions.GettingUsersByDepName)
    UsersByDepService.get_users_by_depName(department.department)
        .then(res => {
            dispatch(UsersByDepActions.GetUsersByDepName(res.data))
            console.log(`users : ${res.data}`)
        })
        .catch(err => {
            dispatch(UsersByDepActions.GettingUsersByDepNameError(err.message))
        })
}

I configured store, reducers and so on…other components work fine.

For the UI I created a small table for displaying the departments and users in that department:

import { AsyncDepartmentsLoad, AsyncDepartmentsAdd, AsyncDeleteDepartmet } from '../../Redux/Reducer/Departments/Departments.Thunk';
import { AsyncGetUsersByDepName } from '../../Redux/Reducer/Departments/UsersByDep.Thunk'

const AdminComponent = () => {
    let countriesCount = 1;
    let departmentsCount = 1;
    let locationsCount = 1;
    let plantsCount = 1;
    let UsersCount = 0;


const DepDispatch = useDispatch();
    const { depIsLoading, departments, depErrorMessage } = useSelector((state) => state.departments)
    useEffect(() => {
        DepDispatch(AsyncDepartmentsLoad())
    }, [DepDispatch]);

    const [depName, setDepName] = useState('');
    const handleDepSubmit = (e) => {
        e.preventDefault();
        const dep = {
            department: depName,
        }
        DepDispatch(AsyncDepartmentsAdd(dep))
        setDepName('');
        setDepartmentShow(false);
    }

<div className='col-6   p-2'>
                            <h3 className='text-center'>
                                <span>
                                    Departments
                                </span>
                                <span className='ms-3'>
                                    <button type='button' className='btn btn-sm btn-secondary' data-toggle="modal" onClick={() => setDepartmentShow(true)} data-target="#addNewItemModal">
                                        +
                                    </button>
                                </span>
                            </h3>
                            <div className='p-2' style={{ minHeight: "400px" }}>
                                <MDBTable hover>
                                    <MDBTableHead>
                                        <tr>
                                            <th scope='col'>#</th>
                                            <th scope='col'>Department name</th>
                                            <th scope='col'></th>
                                            <th scope='col'></th>
                                        </tr>
                                    </MDBTableHead>
                                    <MDBTableBody>

                                        {isLoading && <p className='text-muted bold'>loading....</p>}
                                        {errorMessage && <p className='p-3 mb-2 bg-danger text-white"'>{errorMessage}</p>}
                                        {departments && departments.map(dep =>
                                            <tr key={dep.id}>

                                                <th scope='col'>{departmentsCount++}</th>
                                                <th scope='col'>{dep.department}
                                                </th>
                                                <th><span>

                                                    {
                                                      
                                                    }

                                                </span></th>
                                                <th scope='col'> <Button variant="danger btn-sm" onClick={() => { DepDispatch(AsyncDeleteDepartmet(dep)) }}>-</Button></th>

                                            </tr>
                                        )}

                                    </MDBTableBody>
                                </MDBTable>

                            </div>
                        </div>
 </div >
                </div >
            </div >
        </>
    )
}

export default AdminComponent

Itried to add

<tr key={dep.id}>
    <th scope='col'>{departmentsCount++}</th>
    <th scope='col'>{dep.department}</th>
    <th><span>
         {
             () => { return DepDispatch(AsyncGetUsersByDepName(dep.department)) } 
         }
    </span></th>
    <th scope='col'> <Button variant="danger btn-sm" onClick={() => {DepDispatch(AsyncDeleteDepartmet(dep)) }}>-</Button></th>
</tr>

but No result.

If I access the link from Axios, for example :

http://localhost:8082/api/departments/IT

I can see the user json which in this Department :

[{
"firstname":"Artiom",
"lastname":"userIT",
"login":"userIT",
"email":"[email protected]",
"isActive":"ACTIVE",
"activity":true,
"password":"admin",
"secret":"admin",
"roles":"ROLE_ADMIN",
"permissions":"IT",
"creationDate":"2023-06-0210:03:33",
"departmentName":"IT",
"plant":"Plant1",
"id":1,
"permissionsList":["ROLE_ADMIN"],
"roleList":["ROLE_ADMIN"]
}]

How can I display at least names of users by departmetn? What I do wrong?

Invalid document reference. Document references must have an even number of segments, but notes has 1.’

Browser Console : Invalid document reference. Document references must have an even number of segments, but notes has 1.

async function updateNote(text) {
const docRef = doc(db, “notes”, currentNoteId)
await setDoc(
docRef,
{ body: text, updatedAt: Date.now() },
{ merge: true }
)
}

I am trying to delete a note from my local array of objects as well s from the firebase. I am a beginner and unable to resolve the problem.

Accessing and updating token stored in client side browser in getServerSideProps() in next js

We’re building an e-commerce project and we implemented jwt token logic. We use next js, react js and node js. I (in front-end) store token and refresh token in localStorage. There is a executeRequest function and all my fetch requests are made with it. If token expires it refreshes token and refetches all the requests. It was working fine till I needed to make the project SEO friendly. Now i need to fetch requests in server side and use returned data in meta tags in several pages like products and product page. The main problem is accessing and updating the token in client browser in server side fetching

Here is what I tried:

import { useRouter } from "next/router";
import React, { useEffect, useState } from "react";
import Product from "../../components/product/Product";
import { withAuth } from "../../components/withAuth";
import { useDispatch, useSelector } from "react-redux";
import Head from "next/head";
import {
  BACKEND_URL,
  fetchProductData,
  fixedPriceCalculator,
  getData,
} from "../../functions";
import useTranslation from "next-translate/useTranslation";
import { setProductData } from "../../store/productSlice";

function ProductPage({ uuid, data }) {
  const router = useRouter();
  const dispatch = useDispatch();
  const { title, description, image, productData } = useSelector(
    (state) => state.product
  );
  const { t } = useTranslation("common");
  const { locale } = router;
  const [breadcrumb, setBreadcrumb] = useState([
    { link: t("products"), active: false },
  ]);

  const afterDataFetched = (data) => {
    let tempBreadcrumbs = [...breadcrumb];
    if (tempBreadcrumbs?.length > 1) {
      tempBreadcrumbs.pop();
    }
    // dispatch(setTitle(data?.name));
    tempBreadcrumbs.push({ link: data?.name, active: true });
    setBreadcrumb(tempBreadcrumbs);
    let tempImages = data?.images?.length ? data?.images : [];
    if (data?.video) {
      tempImages.push({ type: "video", video: data?.video });
    }
    data = {
      ...data,
      discountPrice: fixedPriceCalculator(
        Number(data?.price) -
          (Number(data?.price) * Number(data?.discount)) / 100,
        data?.currency
      ),
      images: tempImages,
    };
    dispatch(
      setProductData({
        ...productData,
        [uuid]: { data: data, loading: false, error: false },
      })
    );
  };

  useEffect(() => {
    afterDataFetched(data);
  }, []);

  useEffect(() => {
    getData(
      {
        url: `${BACKEND_URL}/v1/items/${uuid}`,
        params: { language: locale, program: "web" },
      },
      (data) => {
        if (data !== "err") {
          afterDataFetched(data);
        } else {
          dispatch(
            setProductData({
              ...productData,
              [uuid]: { data: "", loading: false, error: true },
            })
          );
        }
      }
    );
  }, [locale]);

  return (
    <>
      <Head>
        <title key="title">{title} | Timar</title>
        <meta name="description" key="description" content={description} />
        {title && (
          <meta
            property="og:title"
            content={`${title} | Timar`}
            key="og:title"
          />
        )}

        {image && (
          <meta
            property="og:image"
            content={`${BACKEND_URL}/images/items/${image}`}
          />
        )}
        <meta property="og:image:type" content="image/png" />
        <meta property="og:image:width" content="1200" />
        <meta property="og:image:height" content="630" />
      </Head>
      <Product uuid={router.query.uuid} breadcrumb={breadcrumb} />
    </>
  );
}

export async function getServerSideProps(context) {
  const { locale, params } = context;
  // Fetch the product UUID from the params
  const { uuid } = params;

  // Fetch the product data using your API fetch function
  const data = await fetchProductData(uuid, locale);

  // Pass the UUID as a prop to the component
  return {
    props: {
      uuid,
      data,
    },
  };
}

export default withAuth(ProductPage);

const refreshTokenFunction = async (refreshToken) => {
  try {
    const response = await axios.post(
      `${BACKEND_URL}/v1/auth/refresh`,
      {
        refreshToken,
        program: "web",
      },
      {
        headers: {
          Authorization: token ? `Bearer ${token}` : "",
        },
      }
    );
    return new Promise((resolve) => {
      localStorage.setItem("token", response.data.token);
      localStorage.setItem("refreshToken", response.data.refreshToken);

      let decodedTokenRefreshed = jwt_decode(response.data.token);
      store.dispatch(setToken(decodedTokenRefreshed));
      resolve(response.data.token);
    });
  } catch (error) {
    if (error.response && error?.response?.status === 409) {
      handleLogout();
      store.dispatch(setIsTokenConflictModalOpen(true));
      Router.push("/");
      return null;
    } else if (error?.response && error?.response?.status === 403) {
      store.dispatch(setIsBlocked(true));
      Router.push("/blocked");
      return "blocked";
    } else {
      throw error;
    }
  }
};

let refreshInProgress = false;
let requestQueue = [];
let requestCounter = 0;

// Function to execute a request with a callback
const executeRequest = async (request, callback, paramToken = "") => {
  token = paramToken || localStorage.getItem("token");
  const { url, method, body = {}, params = null } = request;
  let refreshTokenBlocked = false;
  try {
    const response = await axios({
      url,
      method,
      data: body,
      params,
      headers: {
        Authorization: token ? `Bearer ${token}` : "",
      },
    });
    callback(response.data, 200);
  } catch (error) {
    if (error.response && error?.response?.status === 401) {
      if (token) {
        if (!refreshInProgress) {
          refreshInProgress = true;
          try {
            refreshToken = localStorage.getItem("refreshToken");
            const refreshResponse = await refreshTokenFunction(refreshToken);
            if (refreshResponse) {
              refreshInProgress = false;
              if (refreshResponse !== "blocked") {
                token = refreshResponse;
                if (token) {
                  // requestQueue.forEach((queuedRequest) =>
                  //   executeRequest(
                  //     queuedRequest.request,
                  //     queuedRequest.callback,
                  //     refreshResponse,
                  //     true
                  //   )
                  // );
                  await Promise.all(
                    requestQueue.map(async (queuedRequest) => {
                      await executeRequest(
                        queuedRequest.request,
                        queuedRequest.callback,
                        refreshResponse,
                        true
                      );
                    })
                  );
                }
              } else {
                refreshTokenBlocked = true;
              }
              requestQueue = [];
              requestCounter = 0;
            }
          } catch (error) {
            callback(null, error?.response?.status);
          }
        }
      }
      // If refresh is already in progress or there's no token, add request to queue
      requestQueue.push({ request: { ...request }, callback });
      requestCounter++;
    } else if (error.response && error?.response?.status === 403) {
      store.dispatch(setIsBlocked(true));
      Router.push("/blocked");
      return "";
    } else {
      console.log(error);
      callback("err", error?.response?.status, error?.response?.data);
    }
  } finally {
    if (!refreshTokenBlocked) {
      requestCounter--;
      if (requestCounter === 0 && requestQueue.length > 0) {
        const queuedRequest = requestQueue.shift();
        executeRequest(queuedRequest.request, queuedRequest.callback);
      }
    }
  }
};

// Function to make a GET request with a callback
export const getData = (fetchData, callback) => {
  const { url, params = null } = fetchData;
  executeRequest({ url, method: "GET", params }, callback);
};

export const fetchProductData = (uuid, locale) => {
  return new Promise((resolve, reject) => {
    getData(
      {
        url: `${BACKEND_URL}/v1/items/${uuid}`,
        params: { language: locale, program: "web" },
      },
      (responseData, status) => {
        if (status === 200) {
          resolve(responseData);
        } else {
          reject(new Error(`Failed to fetch product data. Status: ${status}`));
        }
      }
    );
  });
};

Should I implement factory pattern if one behaviour is common and rest are unique?

What problems are solved by factory design patterns?

I have studied Design Patterns: Elements of Reusable Object-Oriented Software but I still find difficulties to understand and implement it.

If I implement a factory design pattern and each object has one common behaviour and the rest are unique. So whether should I implement a factory design pattern for this or create a plain class?

How to evenly distribute elements in a div in a dynamic fashion?

How do I style a div so that equal size elements are always evenly spaced from each other horizontally and vertically regardless of window size?

For example: Lets say a div has 6 elements. When window size is small they would be in 3 rows of 2. And when window size gets big enough to allow 3 in a row to fit, then it would be 2 rows of 3. But when window size gets big enough to allow 4 in a row to fit, it would still keep 2 rows of 3 and instead the space between each element increases.

Click here for the codepen link for my attempt below:

<div class="container-main">
  <div class="container">
    <div class="box">A</div>
    <div class="box">B</div>
    <div class="box">C</div>
    <div class="box">D</div>
    <div class="box">E</div>
    <div class="box">F</div>
  </div>
</div>
.container-main{
  
  display: flex;
  background-color: blue;
  width: 100%;
  height: 500px;
  justify-content: space-evenly;
 
}
.container{

  width: 300px;
  height: 300px;
  display: flex;
  justify-content: space-evenly;
  flex-wrap: wrap;
  background-color: red;
  align-content: space-evenly;
}

.box{
  width: 70px;
  height: 50px;
    background-color:#333;
    padding:20px;
    border-radius:10px;
    color:#fff;
    display:flex;
    align-items:center;
    justify-content:center;
    font-size:40px;
    font-family:sans-serif;
  }

As you can see in the figures below, when the .container width is 300px and 400px it is getting evenly distributed in the whole area of the div. But at 500px and 600px widths, it is no longer evenly distributed (2×3). How do I style it so that the elements always evenly fill up the entire div regardless of its width?


Container width: 300px


Container width: 400px


Container width: 500px


Container width: 600px

Javascript Object method returns undefined value

I have a code snippet like below.

let user = {  
    firstName : "Sunil",  
    lastName : "Kumar",  
    fullName : function(){  
        return this.firstname + " " + this.lastName;  
    }  
}; 

When i call user.fullName() the output is ‘undefined Kumar

Why do I get undefined for the firstName and the actual string for the lastName? Can somebody explain me?

HTML Video tag Strange behavior when controling video progress

When I used the HTML video tag, I found that different videos have different loading behaviors.

The second strange behavior make the playback very awkward.

Both of the videos format is mp4.

Normal behavior:The chrome browser requests video resources,the size of the resource per request is large

Strange behavior: The chrome browser keeps making requests, and there are very few resources per request

but Firefox rarely show this strange behavior.

Is there any principle that can explain this?

Count exact instances of element in array and return True or False

I have two arrays

first= [1,1,1,1,1,2,2,2,2]

second =[1,1,1,1,1]

The javascript function should return True only when all elements in second array is present in first array and if second =[1,1,1,1] or [1,1,1],[1,1],[1],[] it should return false.

Thanks in advance! Cheers

I tried this but doesn’t work for other instances.

function allElementsPresent(first, second) {
  return second.every((element) => first.includes(element));
}

How to transition text along with a circle in CSS animation?

The code I am developing is for mobile site and the animation I expect is as following: Firstly a bigger circle appears such that it covers the whole screen looking like a splash screen and afterwards the bigger circle will transition into smaller circle towards bottom left. Along with that image inside the bigger circle will transit towards bottom left.

The Problem is circle is transitioning properly but the text is not going to bottom left properly it kind of goes to left and then goes down. Below is the code that I tried.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <title></title>
        <style type="text/css">
            .test {
                position: fixed;
                left: 0;
                bottom: 0;
                width: 40px;
                display: flex;
                align-items: center;
                justify-content: center;
                height: 40px;
                transition: all 3s ease;
                background: gray;
                transform: scale(100);
                border-radius: 30px;
                left: 20px;
                bottom: 20px;
            }
            .test.active {
                transform: scale(1);
                transition: all 2s ease;
                left: 20px;
                bottom: 20px;
            }
            .wrapper {
                position: relative;
                display: flex;
                align-items: center;
                justify-content: center;
                height: 100vh;
            }
            .myclass {
                width: 100%;
                height: 100%;
                display: flex;
                align-items: center;
                justify-content: center;
            }
            .before {
                display: flex;
                align-items: center;
                justify-content: center;
                transition: all 2s ease-in-out;
                width: 50%;
                height: 50%;
                position: fixed;
                font-size: 50px;
            }
            .before.active {
                left: 20px;
                bottom: 20px;
                width: 40px;
                height: 40px;
                font-size: 15px;
                position: fixed;
                transform: translate(0, 0);
            }
        </style>
    </head>
    <body>
        <div class="wrapper">
            <div id="test" class="test"></div>
            <div class="myclass">
                <img src="./logo.svg" id="icon-img" class="before"></img>
            </div>
        </div>
        <script>
            setTimeout(function () {
                let i = document.getElementById("test");
                let d = document.getElementById("icon-img");

                i.classList.add("active");
                d.classList.add("active");
            }, 2000);
        </script>
    </body>
</html>

about the remove() function,how can i del the last element only?

I have the problem is that,When i press remove button,whole list is deleted,
for example,i add ABC and DEF,this 2 parts,
I press one time and ABC also gone!
how can i fix it?

<!DOCTYPE html>
<html>
  <head>
    <title>To-Do List</title>
  </head>
  <body>
    <h1>To-Do List</h1>`
    <input type="text" class="task" placeholder="Enter a task">
    <button class="Add">Add Task</button>
    <button class="removeTask">Remove</button>
    <ul class="taskList"></ul>
  </body>
  <script>



const taskList = document.querySelector(".taskList");
const RemoveEl = document.querySelector(".removeTask");
const addTask = document.querySelector(".Add");


addTask.addEventListener("click", (e)=>{ 
  const taskInput = document.querySelector(".task");
const newTask = document.createElement("li");
let task = taskInput.value;

  if (task.trim() != "") {
    
    newTask.innerText = task;
    taskList.appendChild(newTask);
    taskInput.value = "";};
  
    if(newTask){
  RemoveEl.addEventListener("click",()=>{

    taskList.remove();

  })
}});
  </script>
</html>

thank you so much!

Why isn’t the map showing up in my React MapGL component with Mapbox API token?

I am following the below you tube tutorial and trying to learn mapbox. I imported github project and used the token but still not map showing up. Can you let me know how to fix it . Providing stackblitz below

https://www.youtube.com/watch?v=JJatzkPcmoI

https://stackblitz.com/edit/github-h2sep1?file=.env.local,src%2FApp.js

<ReactMapGL
        {...viewport}
        mapboxApiAccessToken={process.env.REACT_APP_MAPBOX_TOKEN}
        mapStyle="mapbox://styles/leighhalliday/cjufmjn1r2kic1fl9wxg7u1l4"
        onViewportChange={viewport => {
          setViewport(viewport);
        }}
      >
        {parkDate.features.map(park => (
          <Marker
            key={park.properties.PARK_ID}
            latitude={park.geometry.coordinates[1]}
            longitude={park.geometry.coordinates[0]}
          >
            <button
              className="marker-btn"
              onClick={e => {
                e.preventDefault();
                setSelectedPark(park);
              }}
            >
              <img src="/skateboarding.svg" alt="Skate Park Icon" />
            </button>
          </Marker>
        ))}

REACT_APP_MAPBOX_TOKEN = “pk.eyJ1IjoicmFqa3VtYXJ0MDgiLCJhIjoiY2xpZmUybjFxMTRkYjNtbzVxYW11azhmbiJ9.u2YJYZcYxi87d0cFw0KD5Q”

Bugs while testing react for asynchronous tasks, Unable to find an element by: [data-testid=”reload-button”]

** Unable to find an element by: [data-testid=”reload-button”]**

Facing issues when testing a create-react-app using RTL.

I’ve a simple react project wherein I’m making a call over the internet to display a list of users. While writing a testcase for the same, I’m trying to mock a fetch call and provide dummy data as well so that my app doesn’t increase load on the server.

But I’m facing issues in this.

I get an error saying:

`Unable to find an element by: [data-testid=”reload-button”]

Ignored nodes: comments, script, style
<body>
  <div />
</body>

  15 |     render(<Body  />)
  16 |
> 17 |     await waitFor(()=>expect(screen.getByTestId("reload-button")))
     |                  ^
  18 |     const usersArray = screen.getAllByTestId("users-list")
  19 |     expect(usersArray.length).toBe(5)
  20 | })

  at waitForWrapper (node_modules/@testing-library/react/node_modules/@testing-library/dom/dist/wait-for.js:166:27)
  at Object.<anonymous> (src/components/__tests___/Body.test.js:17:18)`

My code is as follows:

The component where an api call is made, using which the state is changed and data is passed on to the as props

//Body.js

const Body = () => {
    const [ users, setUsers ] = useState([])
    const  [ reloadUsers , setReloadUsers] = useState(false)
    useEffect(() =>{
        fetchUsers()
    },[reloadUsers])

    const fetchUsers = async () => {
        const data = await fetch(`https://randomuser.me/api/?results=5`) 
        const jsonData = await data.json()
        setUsers(jsonData?.results)
    }
    if(!users)return null

    return users.length===0 ? <p>Loading...</p> :  (
        <div>
            <button 
               data-testid='reload-button' 
               onClick={()=> setReloadUsers(prev => !prev) } >
               Load different users
            </button>
            <UserList users={users}  />
        </div>
      )
}

The component receiveing the data as props and then mapping over it to display the data

//UserList.js

const UserList = ({users}) => {
    const displayList = users.map(user=>(
        <li data-testid="users-list"  
            style={{'display' : 'flex' , 'alignItems' : 'center' , 'margin' : '20px'}}  
            key={user?.login?.uuid} 
        >
            <img  
              style={{'borderRadius':'30px' , 'marginRight' : '20px'}} 
              src={user?.picture?.thumbnail} alt='thumbnail'  />
            <span>{user?.name?.first} {user?.name?.last} </span>
        </li>
    ))
  return (
    <div>
        <h5>UserList</h5>
        <ul style={{ 'listStyleType' : 'none' }} >
            {displayList}
        </ul>
    </div>
  )
}


My test file is as follows where I’m testing if the mock data is getting populated

//Body.test.js

import { render, screen, waitFor } from "@testing-library/react"
import Body from "../Body"
import { usersList } from "../utils/constants";

test('user list should appear on screen', async ()=>{

    global.fetch = jest.fn(()=>{
        return Promise.resolve({
            json : () => {
                return Promise.resolve(usersList)
            }
        })
    })

    render(<Body  />)

    await waitFor(()=>expect(screen.getByTestId("reload-button")))
    const usersArray = screen.getAllByTestId("users-list")
    expect(usersArray.length).toBe(5)
})

What is the mistake that I’m doing?

A more organic way to resolve and return a resolved promise from a JavaScript/Node function than using Promise.resolve?

For instance, I’m writing a Mongoose utility method, and I’m wanting to return a value after the async methods resolve. This is a highly simplified example.

const testConnect = () => {
    let msg;
    mongoose.connect(mongoServer.getUri())
        .then(() => {
            msg ="Connection success!";
        })
        .catch((err) => {
            msg = "Connection failure! Error: " + err;
        });
    return Promise.resolve(msg);
};

My test buildup utilizes this method in a matter like this.

beforeAll(() => {
    iMDT.testConnect()
        .then((result) => {
            console.log(result);
        })
        .catch((err) => {
            console.log(err);
        });
});

Is there a simpler, more organic way to return that value as a resolved promise – without using the prototype Promise? It feels kludgy to me.