How to rewrite the code using conditional rendering in react and javascript?

i have code like below

const mode = isActiveMode;

{!isActiveMode && runId && !isEmpty(items) && (
    <>
        <Flex>
            //more jsx similar
            <Icon onClick={() => 
                setItemState((previous: any) => ({
                    ...previous,
                    items: undefined,
                }))
            }
        />
        <TabPanel>
            <Table />
        </TabPanel>
    </>
)}

{isActiveMode && runId && !isEmpty(items) && isTableOpen && (
    <>
        <Flex>
            //more jsx similar
            <Icon onClick={() => 
                setItemState((previous: any) => ({
                    ...previous,
                    items: undefined,
                }))
            }
        />
        <TabPanel>
            {selections.length === 1 ? (
                <Table/> ): ( <div>hello</div>)
            }
        </TabPanel>
        
            
    </>
)}

i have two renderings based on different conditions. the code inside is almost same in both cases. how can i reuse the code in this case. could someone please help me with this.

How can i rewrite above code into one with conditions using reusable code. thanks.

How to make a structuredClone of a Proxy object?

I’m using Vue3 where a lot of the objects are Proxy objects for reactivity. I want to create a deep copy of one of the proxy objects and recently discovered structuredClone.

https://developer.mozilla.org/en-US/docs/Web/API/structuredClone

When I run the following code, I get an error performing a structuredClone on proxyObj:

const obj = {
    name: "Steve",
    age: 50
}
const handler = {}
const proxyObj = new Proxy(obj, {})

console.log(proxyObj)

const objCopy = structuredClone(obj)

console.log(objCopy)

const proxyObjCopy = structuredClone(proxyObj)
console.log(objCopy)

Uncaught DOMException: Failed to execute ‘structuredClone’ on ‘Window’: # could not be cloned.

Is there a way I can clone the proxy object? Is there a way I can dereference it first, copy it, and not lose the reactivity? Any help is appreciated!

CSS animation to repeat every nth second

I am animating a svg element currently like following

 .r1 {
        
     animation-name: simpleRotation,xRotation;
     animation-delay: 0s, 2s;
     animation-duration: 2s;
     animation-iteration-count: 1, 1;
     animation-timing-function: linear;
     animation-direction: normal;
     animation-fill-mode: forwards;
}

@keyframes simpleRotation {
     from {
         transform: rotate(0deg);
         transform-box: fill-box;
         transform-origin: 50% 50%;  
    }
     to {
         transform: rotate(359deg);
         transform-box: fill-box;
         transform-origin: 50% 50%;  
    }
}
@keyframes xRotation {
     from {
         transform: rotateX(0deg);
         transform-box: fill-box;
         transform-origin: 50% 50%;  
    }
     to {
         transform: rotateX(359deg);
         transform-box: fill-box;
         transform-origin: 50% 50%;  
    }
}
<svg id="Layer_1" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200">
<rect class="r1" id="r1" x="10" y="10" width="10" height="10" stroke="black" stroke-width="0.25" fill="orange"></rect>    
    </svg>

Is it possible to queue the animations (with javascript) in a way so that every 2s the animation runs one after another in a loop such as simpleRotation(0-2s);xRotation(2-4s);simpleRotation(4-6s);xRotation(6-8s);simpleRotation(8-10s);.....

Asking the user to re-enter year of birth until birth year < current year

I have a problem that how to keep show a prompt until user enter their birth year is always smaller than the current year. Here is my code I try using loop but now i struggle. I hope someone can help me, I appreciate it.

<body>
<p id= "age"></p>
<button onclick=" notify()">Try it</button>
<script>
function notify(){
let age = prompt("Your birth year");
        const year = new Date().getFullYear();
        do {
          document.getElementById("age").innerHTML =
            age + " is a good year";
        } while (age < year && age != null);
}
</script>
</body>

Getting number of queries in a MongoDB collection in NodeJS

New to MongoDb, I am working on a small phonebook application where the user can add and remove phonebook entries using a name and phone number. I am able to successfully add and delete entries and have the database updated successfully, but not sure how to get the number of total entries/queries in a specific MongoDB collection.

MongoDB module:

const mongoose = require('mongoose')
const url = process.env.MONGODB_URI
console.log('connecting to', url)

mongoose.connect(url)
.then(result => {
    console.log('connected to MongoDB')
  })
.catch((error) => {
    console.log('error connecting to MongoDB:', error.message)
})

const personSchema = new mongoose.Schema({
    name: String,
    number: String,
}, { collection: 'phonebook' })

personSchema.set('toJSON', {
  transform: (document, returnedObject) => {
    returnedObject.id = returnedObject._id.toString()
    delete returnedObject._id
    delete returnedObject.__v
  }
})

module.exports = mongoose.model('Person', personSchema)

On my MongoDB cluster, the name of my DB is ‘myFirstDatabase’ and the collection name is ‘phonebook’

Current DB looks like this:
enter image description here

On index.js:

app.get('/info', (request, response) => {
    const date = new Date();
    const numPersons = Person.countDocuments()
    //Should be 2
    response.send(`Today is ${date} </br>There are ${numPersons} entries in the phonebook`)
})

Convert these nested functions from arrow to old style and what happens with variables

I’m trying to find items from one list that are not in items in a second list. Almost by dumb luck I got it to work, but only with arrow functions. For me normal functions are easier to read so I tried converting it and the result isn’t what I expect.

data:

const arr1 = [
    {
        "key": 1,
        "val": "one"
    },
    {
        "key": 2,
        "val": "two"
    },
    {
        "key": 3,
        "val": "three"
    }
]

const arr2 = [
    {
        "key": 3,
        "val": "three"
    },
    {
        "key": 4,
        "val": "four"
    },
    {
        "key": 1,
        "val": "one"
    }
]

version 1

arr1.filter((element) => arr2.findIndex((innerElement) => element.key === innerElement.key) === -1); 
// produces object with key 2

version 2

arr1.filter(function(element) { 
    return arr2.findIndex(function(innerElement) { 
      element.key === innerElement.key === -1
    })
}) // produces all three objects in arr1

To make the correct one more terse I removed extra parentheses and it still works:

arr1.filter(element => arr2.findIndex(innerElement => element.key === innerElement.key) === -1);

I’m missing a key aspect here. I get that each item in arr1 is passed to a function and that inner function in turn passes its result to another function and the expression has access to both sets of arguments and gets executed. But I think I have the wrong mental model about the order or something.

Can someone explain what is happening in each step and how to think about it? And how do I make it into a normal function?

I’ll be dealing with a lot of nested structures and I feel this is a weak area that I’d like to get better in.

Thank you

I am changing the state of the REACT component from another component but no refresh

I need a light to see what is missing?.
I am changing the state of the Users REACT component when I add a user to the backend.
The user added with no issues.
And I send the state of the User element in and I change the state when “onSubmit:” happened
but the Users REACT component didn’t reload .
What is wrong with this approach?

const addPlayer = async (firstName, lastName) => {
    await fetch(PlayersBackend, {
        method: 'POST',
        mode: 'cors',
        cache: 'no-cache',
        credentials: 'same-origin',
        headers: {
            "Content-Type":"application/json",
        },
        body: JSON.stringify({ firstName, lastName })
    })
    
};


const AddPlayerForm=(compUsersState) =>{
    const formik = useFormik(
        {initialValues:{firstName: '',lastName: '',},
            validate,
            onSubmit: (values,{resetForm}) =>
        {  addPlayer(values.firstName,values.lastName).then();
            resetForm();
            console.log(compUsersState.compUsersState)
            compUsersState.compUsersState(p => p+1);

        },
    });
    return (
        <form onSubmit={formik.handleSubmit}>
            <label htmlFor="firstName">First Name</label>
            <input
                id="firstName"
                name="firstName"
                type="text"
                onChange={formik.handleChange}
                value={formik.values.firstName}
            />
            <label htmlFor="lastName">Last Name</label>
            <input
                id="lastName"
                name="lastName"
                type="text"
                onChange={formik.handleChange}
                value={formik.values.lastName}
            />

            <button type="submit">Add user</button>
        </form>
    );
};

export const Users = () => {

    const [error, setError] = useState(null);
    const [isLoaded, setIsLoaded] = useState(false);
    const [users, setPlayers] = useState([]);
    const [,compUsersState] = useState(0);
    useEffect(() => {
        fetch(PlayersBackend).then(response => response.json()).then((data) => { setIsLoaded(true);setPlayers(data);}, (error) => {setIsLoaded(true);setError(error);})},[])
    if (error) {
        //console.log(error.message);
        return <div>Error: {error.message}</div>;
    } else if (!isLoaded) {
        return <div>Loading...</div>;
    } else {

        if (typeof (users._embedded) !== 'undefined')
        {
            return (

                <ul>
                    <AddPlayerForm compUsersState={compUsersState}/>
                    {users._embedded.players.map(player => (
                        <li className="d-flex justify-content-start" key={unique_id()}>
                            {player.firstName} {player.lastName}
                        </li>
                    ))}

                </ul>
            );

        }
        else return  (<ul> </ul> )

    }

}```

Auto Selecting a Value from Dropdown on Selection of Specific Value from Another Dropdown

Basically I am trying to figure out on selecting a value from dropdown on selection of a value from another dropdown select box.

var gender1 = document.querySelector("#gender1");
var gender2 = document.querySelector("#gender2");

gender1.addEventListener("change", function() {
  var value = gender1.value;
  switch (value) {

    case "Boy":
      gender2.value = "Tipu";
      break;

    case "Girl":
      gender2.value = "Ayubi";
      break;

  }
})
<select class="input_select" name="student_gender" id="gender1">
  <option value="Boy" '.$selected_boy.'>Boy</option>
  <option value="Girl" '.$selected_girl.'>Girl</option>
</select>

<select class="input_select" name="student_class_section" id="gender2">
  <option value="Tipu" '.$selected_boy.'>Tipu (Boy)</option>
  <option value="Ayubi" '.$selected_girl.'>Ayubi (Girl)</option>
</select>

Remove dynamicly created select2 selected value from the list of ajax data

i have this Api, thi api fetch data to feed select2 ajax

 public async Task<IActionResult> Search(string term)
    {
        try
        {
            var data = await _context.ScrapCodes
                .Where(sc => sc.Name.Contains(term) || sc.Code.ToString().Contains(term))
                .ToListAsync();
            return Ok(data);
        }
        catch (Exception)
        {
            return Ok();
        }
    }

this function will initialize select 2 form with new id

function initializeSelect2(elem) {
            elem.select2({
                placeholder: "search here",
                allowClear: true,
                width: 'resolve',
                ajax: {
                    url: "/api/digitalization/search",
                    contentType: "application/json; charset=utf-8",
                    data: function (params) {

                        var query =
                        {
                            term: params.term,
                        };
                        return query;
                    },
                    headers: {
                        "RequestVerificationToken":
                            $('input[name="__RequestVerificationToken"]').val()
                    },
                    processResults: function (data) {
                        return {
                            results: $.map(data, function (item) {
                                return {
                                    id: item.code,
                                    text: item.code + ' - ' + item.name
                                }
                            })
                        }
                    }
                }
            });
        }

this button function to add new select2 eachtime it clicked

 $("#add_select").on("click", function () {
            var div1 = $("<div id ='scp_"+ele+"' class='col-md-8'>");
            var div2 = $("<select id='scrap_code" + ele + "' name='scrap_code" + ele + "' class='form-control _select2' placeholder='Code scrap' />");
            var div3 = $("</div>" +
                "<div class='col-md-4'>" +
                "<input id='scrap_val" + ele + "' name='scrap_val" + ele + "' class='form-control' placeholder='jumlah scrap' />" +
                "</div>");
            var div4 = $("<input type='button' id='_delete"+ele+"' value='Remove' />");
            $("#id_select").append(div1);
            $("#id_select").append(div2);
            $("#id_select").append(div4);
            $("#id_select").append(div3);
            
            initializeSelect2(div2);
            ele++;
            startElement.val(++value);
            $(div4).on('click', function (e) {
                e.preventDefault();
                $(div2).select2('destroy');
                var elem = document.parentElement(div4);
                elem.parentNode.removeChild(elem)
                startElement.val(--value);
            });

        });

What should i do if i want to remove selected item from select list each time the value is selected from dynamicly created select2 form?

Passing a child component(drop down) to the parent component with React-Hook-Forms: ref is not a prop & no values saved when submitted

I have this drop-down (select) component named Size as a child component. I have nested useFieldArray in the parent component as well. And I’ve been receiving warnings every time I’ll submit it and no values are being displayed in the console as well. What is happening and how can I fix it?

These are the errors:

Warning: Size: ref is not a prop. Trying to access it will result in
undefined being returned. If you need to access the same value
within the child component, you should pass it as a different prop.

Field is missing name attribute …

Link to codesandbox:
https://codesandbox.io/s/react-hook-form-usefieldarray-nested-arrays-forked-vjwbp?file=/src/Drop_drowns/Size.js

Size.js

import { InputLabel, MenuItem, FormControl, Select } from "@mui/material";

const Size = ({ name, ref, defaultValue }) => {
  return (
    <FormControl fullWidth variant="filled">
      <InputLabel id="Size Label">Size</InputLabel>
      <Select
        labelId="Size"
        id="size"
        name={name}
        label="Product"
        ref={ref}
        defaultValue={defaultValue}
      >
        <MenuItem value="S">Small</MenuItem>
        <MenuItem value="M">Medium</MenuItem>
        <MenuItem value="L">Large</MenuItem>
      </Select>
    </FormControl>
  );
};

export default Size;

Nested Field Array:

import React from "react";
import { useFieldArray } from "react-hook-form";
import Size from "./Drop_drowns/Size";
import { TextField } from "@mui/material";

export default ({ nestIndex, control, register }) => {
  const { fields, remove, append } = useFieldArray({
    control,
    name: `test[${nestIndex}].nestedArray`
  });

  return (
    <div>
      {fields.map((item, k) => {
        return (
          <div key={item.id} style={{ marginLeft: 20 }}>
            <label>Colors:</label>
            <Size
              name={`test[${nestIndex}].nestedArray[${k}].field1`}
              ref={register({ required: true })}
              defaultValue={item.field1}
              style={{ marginRight: "25px" }}
            />
            {/* <input
              name={`test[${nestIndex}].nestedArray[${k}].field1`}
              ref={register({ required: true })}
              defaultValue={item.field1}
              style={{ marginRight: "25px" }}
            /> */}

            <TextField
              name={`test[${nestIndex}].nestedArray[${k}].field2`}
              ref={register()}
              defaultValue={item.field2}
            />

            <TextField
              name={`test[${nestIndex}].nestedArray[${k}].field3`}
              ref={register()}
              defaultValue={item.field3}
            />
            <button type="button" onClick={() => remove(k)}>
              Delete Colors
            </button>
          </div>
        );
      })}

      <button
        type="button"
        onClick={() =>
          append({
            field1: "field1",
            field2: "field2"
          })
        }
      >
        Add Colors
      </button>

      <hr />
    </div>
  );
};

fieldArray:

import React from "react";
import { useFieldArray } from "react-hook-form";
import NestedArray from "./nestedFieldArray";
import { TextField } from "@mui/material";

let renderCount = 0;

export default function Fields({ control, register, setValue, getValues }) {
  const { fields, append, remove, prepends } = useFieldArray({
    control,
    name: "test"
  });

  renderCount++;

  return (
    <>
      <ul>
        {fields.map((item, index) => {
          return (
            <li key={item.id}>
              <TextField
                name={`test[${index}].name`}
                ref={register()}
                defaultValue={item.name}
              />

              <button type="button" onClick={() => remove(index)}>
                Delete
              </button>
              <NestedArray nestIndex={index} {...{ control, register }} />
            </li>
          );
        })}
      </ul>

      <section>
        <button
          type="button"
          onClick={() => {
            append({ name: "append" });
          }}
        >
          Add product
        </button>

        {/* <button
          type="button"
          onClick={() => {
            setValue("test", [
              ...getValues().test,
              {
                name: "append",
                nestedArray: [{ field1: "append", field2: "append" }]
              }
            ]);
          }}
        >
          update product
        </button> */}
      </section>

      <span className="counter">Render Count: {renderCount}</span>
    </>
  );
}

index.js

import React from "react";
import { useForm } from "react-hook-form";
import FieldArray from "./fieldArray";
import ReactDOM from "react-dom";

import "./styles.css";

const defaultValues = {
  test: [
    {
      product: "",
      nestedArray: [{ field1: "", field2: "", field3: "" }]
    },
    {
      product: "",
      nestedArray: [{ field1: "", field2: "", field3: "" }]
    }
  ]
};

function App() {
  const {
    control,
    register,
    handleSubmit,
    getValues,
    errors,
    reset,
    setValue
  } = useForm({
    defaultValues
  });
  const onSubmit = (data) => console.log("data", data);

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <h1>Array of Array Fields</h1>
      <p>
        The following example demonstrate the ability of building nested array
        fields.
      </p>

      <FieldArray
        {...{ control, register, defaultValues, getValues, setValue, errors }}
      />

      <button type="button" onClick={() => reset(defaultValues)}>
        Reset
      </button>

      <input type="submit" />
    </form>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Why is export from index.tsx file undefined? (React + Typescript)

I have a simple Context Provider that I want to export as a npm package.
I have created an index.tsx file that will be accessible when importing this npm package from another project;
I am importing the Context Provider to this index.tsx, then exporting it.

When I try and run a test with the ContextProvider imported from index.tsx, the imported object is undefined (even though I can navigate to it in VS Code). However, when I import it directly from the source, it works fine. I will need to have it working from the index.tsx file in order to access it through the npm package.

Can anyone explain to me what I’m missing here?

src/index.tsx

import ErrorHandler from './contexts/ErrorHandlerContextProvider'

export { ErrorHandler }

// export { default as ErrorHandler } from './contexts/ErrorHandlerContextProvider' //<-- no luck

src/index.test.tsx

// import ErrorHandler from './contexts/ErrorHandlerContextProvider' // <-- this import works
import { ErrorHandler } from '.'

describe('ErrorHandlerContextProvider', () => {
  it('is truthy', () => {
    expect(ErrorHandler.ErrorHandlerContextProvider).toBeTruthy()
  })
})

src/contexts/ErrorHandlerContextProvider.tsx

import React, { createContext, FC, useContext } from 'react'
import PropTypes from 'prop-types'

type errorHandlerContextType = {
  handleError: (error: Error, info: string) => Promise<void>
}

const ErrorHandlerContext = createContext<errorHandlerContextType | null>(null)

const useErrorHandlerContextProvider = () => {
  return useContext(ErrorHandlerContext)
}

const ErrorHandlerContextProvider: FC = ({ children }) => {

  const handleError = (error: Error, info: string): Promise<void> => {
    console.log('error', error)
    console.log('info', info)

    return Promise.reject(error)
  }

  return (
    <ErrorHandlerContext.Provider value={{ handleError }}>
      {children}
    </ErrorHandlerContext.Provider>
  )
}

ErrorHandlerContextProvider.propTypes = {
  children: PropTypes.node.isRequired
}

export default { ErrorHandlerContextProvider, useErrorHandlerContextProvider }

npm run test

FAIL src/index.test.tsx
● ErrorHandlerContextProvider › is truthy

TypeError: Cannot read property 'ErrorHandlerContextProvider' of undefined

  4 | describe('ErrorHandlerContextProvider', () => {
  5 |   it('is truthy', () => {
> 6 |     expect(ErrorHandler.ErrorHandlerContextProvider).toBeTruthy()
    |                         ^
  7 |   })
  8 | })
  9 |

  at Object.<anonymous> (src/index.test.tsx:6:25)