How to conditionally render 3 different lists in React?

As you can see from the code, at first I want all the todos to be shown, then toggle between all, active and completed todos. I have made the arrays for the active and completed todos, but I’m not quite sure how to implement the switching between those lists. For example, how can I render only active todos instead of the all the todos, etc.?

return (
    <div className='card'>
      <TodoForm addTodo={addTodo} />
      <div className='list-group'>
              {
            todos.map((item, index) =>
              item.isEditing ? <TodoEditForm item={item} key={index} editTask={editTask} /> :
                <Todo item={item} key={index}
                  toggleCompleted={toggleCompleted}
                  removeTodo={removeTodo}
                  toggleEdit={toggleEdit} />
            )
              }

          {
            bool ? 
            <div>
              Active
            </div> 
            :
            <div>
              Completed
            </div>
          }
      </div>
      <div className='toggle-todos-wrapper'>
        <button className="toggle-todos-button btn btn-light">All</button>
        <button className="toggle-todos-button btn btn-light">Active</button>
        <button className="toggle-todos-button btn btn-light">Completed</button>
      </div>
    </div>
  )
}

export default TodoWrapper

I tried using the ternary operator to switch between the active and completed todos, but the all todos remain.

When install tailwind, styles from vite and css file still apply even though they are deleted

I installed tailwind and other tools using npm install -D tailwindcss postcss autoprefixer vite as tailwind doc says

Configure tailwind.config.js

export default {
  content: [
    "./index.html",
    "./src/**/*.{js,ts,jsx,tsx}",
  ],
  theme: {
    extend: {},
  },
  plugins: [require("daisyui")],
}

Add the Tailwind directives to index.css

@tailwind base;
@tailwind components;
@tailwind utilities;

And tailwind works, but old style from Vite still apply.
Example:
[1]: https://i.stack.imgur.com/gvzpM.png

Somehow i get dark background from vite example count. I deleted all files but they still apply.

Convert USDC inputdata into $

I’m trying to format my inputdata (USDC) on Optimism (Ethereum L2) into $. But I’m having problems doing it correctly, I’m just got lost along the way and some help would be super appreciated.

TransactionDescription { fragment: FunctionFragment { type: 'function', inputs: [ [ParamType], [ParamType] ], name: 'transfer', constant: false, outputs: [ [ParamType] ], stateMutability: 'nonpayable', payable: false, gas: null }, name: 'transfer', args: Result(2) [ '0xAe25A77345B4C823C92908AbdF813B36E855C5eB', 16000000000n ], signature: 'transfer(address,uint256)', selector: '0xa9059cbb', value: 0n }

The data I have is the 2 value in args, I have to turn that into USDC $ value to show the user. When I do it, I never get it quiet right its always a number thats too long

I tried using packages to convert them but they all didnt help, I think it might be because of my data? Maybe most people use another piece of data to format USDC, I dont know.

How do I get these arrays to be equal to each other?

I’m cleaning up a game of tic-tac-toe I made a while back because I’m bored but I ran into a problem. The items are different because whenever I use .push or .splice on them it adds “” around the numbers. Can anyone help me fix this?

const winningCombos = ["123", "456", "789"];
const myCombos = [];
myCombos.splice(0, 0, "2");
console.log(myCombos);
myCombos.splice(0, 0, "1");
console.log(myCombos);
myCombos.push("3");
console.log(myCombos);
if (winningCombos[0] === myCombos[0]) {
  console.log("Success")
} else {
  console.log("Fail")
}

All I want it to do is it to end with the console saying Success and the numbers being equal to 123. Can anybody help me?

How to add an edit functionality in a todo list project using vanilla javascript

I really need some help with my todo list project. everything is fine but I can’t seem to make the edit feature work on my todos, I finally knew to some extent how to change the desired todo title, description, etc but whenever I try to change one todo it changes the other todos as well. I’ve spent nearly 1 day trying to make this exact functionality to work
here is my code:
form-edit-submit.js

import { todos } from "./storetodos.js";
const editTodoForm = document.getElementById("edit-todo");
const darkOverlay = document.getElementById("dark-overlay");
function editTodos(element) {
  editTodoForm.addEventListener("submit", saveEdit);
  function saveEdit(ev) {
    ev.preventDefault();
    const titleEditValue = document.getElementById("title-edit").value;
    const descriptionEditValue = document.getElementById("textarea-edit").value;
    const dueDateEditValue = document.getElementById("date-edit").value;
    const lowPriorityEditButton = document.getElementById("low-edit");
    const midPriorityEditButton = document.getElementById("mid-edit");
    const highPriorityEditButton = document.getElementById("high-edit");
    element.title = titleEditValue;
    element.description = descriptionEditValue;
    element.dueDate = dueDateEditValue;
    if (lowPriorityEditButton.style.border.includes("solid")) {
      element.priority = "low";
    } else if (midPriorityEditButton.style.border.includes("solid")) {
      element.priority = "mid";
    } else if (highPriorityEditButton.style.border.includes("solid")) {
      element.priority = "high";
    }
    editTodoForm.style.display = "none";
    darkOverlay.classList.remove("dark-overlay2");
    console.log(element);
  }
}
export { editTodos };

todo-buttons.js:

function todoEditButton() {
  content.addEventListener("click", function (ev) {
    for (let i = 0; i < todos.length; i++) {
      const element = todos[i];
      if (ev.target.todoID === element.todoID && ev.target.classList.contains("edit")) {
        const resID = ev.target.todoID;
        editTodoForm.style.display = "block";
        darkOverlay.classList.add("dark-overlay2");
        const res = todos.find(function (item) {
          return item.todoID === resID;
        });
        editTodos(res);
        break;
      }
    }
  });
}

Also here is my github repository: https://github.com/BodiAli/todo-list
here it is live: https://bodiali.github.io/todo-list/

CastError author

im working on a MEAN stack project , i have a user can post an article on after getting logged on.
in page of user login ; i can make dynamic name by post with {{author.name}} and get his image (+author.image) too.
i want to do the same on the home page displaying all the articles of all users but i can’t get image and name under every article ! ? i need some help plz

this is blog HTML :

        </div>
            <div class="card-footer border-top-0 bg-transparent p-0">
              <ul class="card-meta list-inline">
                <li class="list-inline-item mt-2">
                  <a href="author-single.html" class="card-meta-author" title="Read all posts by - Thomas Macaulay">
                    <img class="w-auto" [src]="'http://127.0.0.1:3000/getimages/'+author.image" width="26" height="26"> by <span>{{author.name}}</span>

                  </a>
                </li>
                <li class="list-inline-item mt-2">•</li>
                <li class="list-inline-item mt-2">
                  <ul class="card-meta-tag list-inline">
                    <li class="list-inline-item small" *ngFor="let t of item.tags"><a href="tag-single.html">{{t}}</a></li>
                  </ul>
                </li>
              </ul>
            </div>

and this is Blog Typescript :

 constructor(private act : ActivatedRoute , private data : DataService , private auth : AuthService ){}
   id : any ;  
   articles : any;
   author : any 

  ngOnInit(): void {

    this.id = this.act.snapshot.paramMap.get('id');
    console.log(this.id);
    this.auth.getbyId(this.id)
    .subscribe((res=>{
      this.author=res;
      console.log(this.author);
    }))
  
    this.data.getArticleByAuthor(this.id)
    .subscribe ( res=>{
      this.articles=res;
    })
  
    this.data.getAll()
    .subscribe(
      res=>{
        this.articles=res;
        console.log(this.articles);
      },
      err=>{
        console.log(err);
      } 
    )
  }
}

it works on my author page like this author page
but not on my home pageHome page

How to read and manipulate files with html/javascript [duplicate]

I’m trying to make a page on my site which allows input of a number of .JSON files, to further combine them into one JSON file. The combined data of which is manipulated and displayed to the user using graphs. I can’t seem to find a way to display this data to the user.

My code is as follows. I have a simple html input which leads into some javascript.

<input type="file" name="filefield" id="fileList" multiple="multiple" accept=".JSON">

<script>
const fileList = document.getElementById("fileList").files;
console.log(fileList[0]);
</script>

I’m trying to output the contents of the JSON file to the console as a test to see that I can access the data. The console however just reads metadata of the given file, not the content within.

Vuelidate dynamically adding a field to array immediately makes it dirty

I am working on a vue 3 app with vuelidate next and have some validations that look like this:

validations: {
    currentUser: {
        name: {
            required,
            maxLength: maxLength(64),
        },
        email: {
            required,
            email,
            maxLength: maxLength(64),
        },
        address: {
            maxLength: maxLength(191),
        },
        password: {
            minLength: minLength(8),
            maxLength: maxLength(64),
        },
        alarm_emails: {
            $each: helpers.forEach({
                alarm_email: {
                    required,
                    email,
                    maxLength: maxLength(64),
                }
            })
        },
        phones: {
            $each: helpers.forEach({
                number: {
                    required,
                    phone,
                }
            })
        }
    },
},

and on a click of a button I am adding a new field using this code:

this.currentUser.alarm_emails.push({alarm_email: '', is_alarm: this.currentUser.is_email_alarm });

and this works but the problem is the new field is immediately dirty and I do not want that.

I’ve been googling for some time and found nothing. I tried:

this.v$.currentUser.$reset();

and similar things but that did not help. I even asked bard about it.

Any ideas?

Playing audio object when state changes

How can I trigger playing audio correctly on constant state change in React?:

const [previousItem, setPreviousItem] = useState()

useEffect(() => {
  if (myArray ? .size > 0) {
    const item = Array.from(myArray.values()).pop()
    if (
      item &&
      !item.isChecked
    ) {
      const audio = new Audio(blipSound)
      audio.play()
      setPreviousItem(item)
    }
  }
}, [myArray, previousItem ? .id])

Sometimes I get sound (it’s just a beeping sound) if though console.log was not hit i.e. didn’t really go inside the if condition. I also get Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first even though it beeps.

TIA!

Tried that code, tried putting audio outside of useEffect.

Why is my WebRTC only working over my local network

So I am setting up WebRTC for the first time and got it working fine on my local network, but when I tried over another network it just stopped working. I have setup a stun server and a turn server but it’s still not working.

This is my configuration, not sure if there could be other factors or other bits of code I should show but this is what I set:

const iceConfiguration = {
  iceServers: [
    {
      urls: "stun:stun.l.google.com:19302"
    },
    {
      urls: 'turn:relay1.expressturn.com:3478',
      username: '', // There is a username and password here i just removed it
      credential: ''
    }
  ]
}

const peerConnection = new RTCPeerConnection(iceConfiguration);

Datatable (Edit Button) doesn’t work on second page

I currently have a table which populates data from my server. However, on the second page and further, the “edit” button no longer works. This issue only happens when I link my table to the Datatable function. Below is the HTML for the table.

<div class="card-body">
                            <div class="table-responsive ">
                                <table id="uni_table" class="display nowrap table table-hover table-striped table-bordered" cellspacing="0" width="100%">
                                    <thead>
                                        <tr>
                                          <!--  <th onclick="sortTable(0)" class="fa fa-fw fa-sort">Employee Name</th> -->
                                            <th>Employee Name</th>
                                            <th>EID</th>
                                            <th>Slips Issued</th>
                                            <th>Gender</th>
                                            <th>Description</th>

                                            <th>Date</th>
                                            <th>Edit</th>

                                            <th>Shirt</th>
                                            <th>Shirt Colour</th>
                                            <th>Pants</th>
                                            <th>Pants Color</th>

                                            <th>Tie</th>
                                            <th>Cap</th>
                                            <th>Insignia Stripe</th>
                                            <th>Crest</th>
                                            <th>Star Nickle</th>

                                            <th>S.O Pin</th>
                                            <th>Epaulettes</th>
                                            <th>Shoes</th>
                                            <th>Jacket</th>




                                        </tr>
                                    </thead>
                                
                                    <tbody>
                                       <?php foreach($uniforms as $value): ?>
                                        <tr>

                                          <!-- Values in Database -->

                                            <td ><?php echo $value->first_name.' '.$value->last_name; ?></td>
                                            <td ><?php echo $value->em_code; ?></td>
                                            <td ><?php echo $value->nos; ?></td>
                                            <td ><?php echo $value->em_gender; ?></td>
                                            <td ><?php echo substr("$value->description",0,25). '...' ?> </td>

                                            <td><button class="btn btn-sm btn-success"><?php echo $value->date; ?></button></td>
                                            <td  class="jsgrid-align-center ">
                                                <a href="#" title="Edit" class="btn btn-sm btn-primary waves-effect waves-light uniformsss" data-id="<?php echo $value->id; ?>"><i class="fa fa-pencil-square-o"></i></a>
                                                <a id="delete_uni" href="DeletUniformSlip?D=<?php echo $value->id; ?>" onclick="confirm('Are you sure to delete this value?')" title="Delete" class="btn btn-sm btn-danger waves-effect waves-light"><i class="fa fa-trash-o"></i></a>
                                            </td>

                                            <td ><?php echo $value->shirt; ?></td>
                                            <td ><?php echo $value->s_color; ?></td>
                                            <td ><?php echo $value->pants; ?></td>
                                            <td ><?php echo $value->p_color; ?></td>
                                            <td ><?php echo $value->tie; ?></td>
                                            <td ><?php echo $value->cap; ?></td>
                                            <td ><?php echo $value->ins_stripe; ?></td>
                                            <td ><?php echo $value->crest; ?></td>
                                            <td ><?php echo $value->st_nickle; ?></td>
                                            <td ><?php echo $value->so_pin; ?></td>
                                            <td ><?php echo $value->epaulettes; ?></td>
                                            <td ><?php echo $value->shoes; ?></td>
                                            <td ><?php echo $value->jacket; ?></td>

                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>

The table populates as it should but the edit button only clicks on the first page. Below is the function I use for the DataTable.

  $('#uni_table').DataTable({
    "aaSorting": [[1,'asc']],
    dom: 'Bfrtip',
    buttons: [
        'copy', 'csv', 'excel', 'pdf', 'print'
    ]
});

How can I have this fixed? Below is a screenshot of the table.
enter image description here

After loading the Expo go project it becomes a white screen. (expo-splash-screen)

After loading the expo-splash-screen, a white screen appears.

App.js

import React, { useCallback, useEffect } from 'react';
import * as Font from 'expo-font';
import { useState } from 'react';
import * as SplashScreen from 'expo-splash-screen';
import MainLogin from './components/navigate';
import { View } from 'react-native';


SplashScreen.preventAutoHideAsync();




export default function App() {
  const [appIsReady, setAppIsReady] = useState(false);

  useEffect(() => {
    async function prepare() {
      try {
        await Font.loadAsync ({
          'CG-Bold': require('./assets/fonts/CormorantGaramond-Bold.ttf')
        });
        await new Promise(resolve => setTimeout(resolve, 2000));
        setAppIsReady(true);
      } catch (e) {
        console.warn(e);
      } finally {
        setAppIsReady(true);
      }
    }

    prepare();
  }, []);

  const onLayoutRootView = useCallback(async () =>{
    if (appIsReady) {
      await SplashScreen.hideAsync();
    }
  }, [appIsReady]);

  if (!appIsReady) {
    return null;
  }

  return(
    <View onLayout={onLayoutRootView}>
    <MainLogin />
    </View>
  );
  
}

I tried to do via if else there was progress in expo go but when I built APK in it was also white screen after loading. I’ve only tried to do. enter image description here

React JS Access GeoLocation variables outside of async function

I am trying get my current coordinates and then pass them to a function to calculate the distance, I know I am in a async method but I cannot reference the other function within it. How can I return this type of function to return the coordinates and I can call the computeDistance method out of it. Thanks


                if ("geolocation" in navigator) {
                  navigator.geolocation.getCurrentPosition(function (position) {
                    lon = parseFloat(position.coords.longitude);
                    lat = parseFloat(position.coords.latitude);

                    let res = this.computeDistance(stop.lat,stop.lon, parseFloat(position.coords.latitude), parseFloat(position.coords.longitude), "K");
                
                  });
                } else {
                  console.log("Geolocation is not available in your browser.");
                }

I have tried binding the function or re ordering the method but it doesnt work. The error I receieve is Cannot read properties of undefined (reading ‘computeDistance’)
TypeError: Cannot read properties of undefined (reading ‘computeDistance’)

Try Catch block in javascript for fuctions that already use try catch

I have this function in Javascript:

async function getData(url) {
    try {
        const response = await axios.get(url);
        return response.data;
    } catch (error) {
        console.error('Error fetching data:', error.message);
        throw new Error(error);
    }
}

I need to use this function in another function:

async function runProject(){
  const await = getData()
}

Should i wrap also getData() in another try catch block, or is ok to use as in my example?

Note: I ask because another try catch block aoround the function looks redundant to me, because if the function will fail the eerro will be trown by the try catch clovk inside the function itself.