In my project, I want to change the clothes of the avatar’s clothes as per the avatar’s wants (limited stock ). And I’m going to make this project using threejs.
So kindly help me ,which approach should I take or any code or any thing which can help me to build this project
Category: javascript
Category Added in a WPeMatico Campaign
LocalStorage not updated with the latest value
I am new to react and I am experimenting with incrementing a value and storing it into local storage. I was able to write down the following code bellow, however, the last instance of the incremented number is not updated the local storage value. For example, if I press “+1” twice and the number is 10, the dom is updated twice and shows the number 12, but the value stored on local storage is 11. Why is this happening?
import { useState } from 'react'
function About () {
const localStorageValue = parseInt(localStorage.getItem('value'))
const [value, setValue] = useState(localStorageValue);
function remove() {
setValue((add) => add - 1)
localStorage.setItem('value', parseInt(value))
}
function add() {
setValue((add) => add + 1)
localStorage.setItem('value', parseInt(value))
}
return (
<>
<h1>About page</h1>
<button onClick={remove}>-1</button>
{value}
<button onClick={add}>+1</button>
</>
)
}
export default About;
Not able to apply my filters only for those 2 dropdowns why?
I can filter my data by clicking on the checkboxes inside my dropdowns except for those 2: comments and types.
I think it’s because for comments, I have an integer that needs to be converted into string. The second one, i don’t know how to deal with. If I choose to filter by small it means display data where small:1, same logic for tall and medium.
export default function Display() {
const { menuId } = useParams();
const [menus, setMenus] = useState([]);
...
const [comments, setComments] = useState([
{ label: "1", value: "1", name: "1", selected: false },
{ label: "2", value: "2", name: "2", selected: false },
{ label: "3", value: "3", name: "3", selected: false }
]);
const [types, setTypes] = useState([
{ label: "medium", value: "medium", name: "Medium", selected: false },
{ label: "tall", value: "tall", name: "Tall", selected: false },
{ label: "small", value: "small", name: "Small", selected: false }
]);
useEffect(() => {
axios.post("", {menuId:parsInt{menuId}) //not my real url
.then((res) => {
const menus = res.data.menus;
setMenus([
...menus.filter((i) => i.status === "Good"),
...menus.filter((i) => i.status !== "Good")
]);
})
.catch((err) => {
console.log(err);
});
}, [menuId]);
const matchDdata = menus.filter(({ id }) => {
return !apply[id];
});
const filters = matchData.filter((menus) => {
const allComments = comments.every((i) => i.selected === false);
const optionComments = comments
.filter((entity) => entity.selected)
.map(({ value }) => value.toString());
const allTypes = types.every((i) => i.selected === false);
const optionTypes = types
.filter((entity) => entity.selected)
.map(({ value }) => value);
const isSelComments =
allComments || optionComments.indexOf(menus.comments) >= 0;
const isSelTypes = allTypes || optionTypes.indexOf(menus.types[0]) >= 0;
return (isSelComments && isSelTypes);});
const reset = (list) =>
list.map((e) => ({
...e,
selected: false
}));
const cancel = () => {
setComments(reset(comments));
setTypes(reset(types));
};
const data = [
{
Header: "id",
accessor: (row) => row.id
},
...
];
return (
<div >
<div>
<Button onClick={cancel}>cancel</Button>
</div>
<div>
<Drop
placeholder={"Types"}
items={types}
onSelect={dropSelection(setTypes)}
hasAll
/>
<Drop
placeholder={"Comments"}
items={comments}
onSelect={dropSelection(setComments)}
hasAll
/>
</div>
<Table
data={filters}
columns={data}
/>
</div>
);
}
Here is my json from my api for menuId:1:
[
{
"id": "Menu1",
"name": "Pea Soup",
"description": "Creamy pea soup topped with melted cheese and sourdough croutons.",
"types": [
{
"small": 0,
"tall": 1,
"medium":0
}
],
"taste": "Good",
"comments": 3,
"price": "Low",
"status": "Pending",
"apply": 1
},
...
]
Styling nested MUI TreeView and TreeItem not working as expected
I’m using TreeView, TreeItem of material ui.
I’m trying to style conditionally each node (selected, hover, focus).
actually what I’m trying to do is that only node that not disabledButton (props that come from outside) will be in right color.
only node that selectable will be in active color (expand node not means that node is selectable).
something like this example

I did this example, but the behavior is really weird, sometimes the “child-4” looks like the style of disabledButton even I sent the right props, maybe because it nested props, sometimes the other nested not get the right colors of the hover, focus and selected..
link for example (with colors)
example with different colors
I want it to be in real colors also with the theme (active should be like blue color, hover gray) so I created this example.
example with theme colors
sometimes it works as expected and sometimes is not.
I looked in this issue but it’s not like my example but there it uses in classes but I don’t want to send this way
JavaScript particles image to image
I’m looking for a particles library in javascript that would allow me to draw an image on canvas and then load a second image, and a third (etc) but with the functionality of using the previous image particles to generate the new one.
I have tried particlejs, threejs, ParticleImageDisplayer, nextparticle and neither has this option.
Is there any that would work?
Thanks.
React native firebase fetch messages realtime
I’m developing a chat application using react native and firebase firestore db, I have almost implemented that part but stuck where I need to listen to changes in my messages collection and get the latest message for current roomId, but everytime the listener listens, it duplicates the last message. I think I may know the reason as I’m using 3 useEffects, 1st for initial room status checking like whether a room is created between current 2 users or not, 2nd for initially fetching all messages if the room exists between the two users, 3rd for realtime listener. Below is the relevant code:
const [messages, setMessages] = useState([]);
const [roomId, setRoomId] = useState('');
useEffect(() => {
// logic to setRoomId
// ...
if (item?.members?.includes(userDetails?.uid)) {
setRoomId(item.roomId);
return true;
}
// ...
}, []);
// fetch all messages initially
useEffect(() => {
if (roomId) {
const q = query(
collection(db, 'messages'),
where('roomId', '==', roomId),
orderBy('createdAt', 'asc'),
);
getDocs(q)
.then(result => {
const messages = result.docs.map(doc => {
const data = doc.data();
return {
id: data?.id,
roomId: data?.roomId,
sentBy: data?.sentBy,
text: data?.text,
user: data?.user,
createdAt: data?.createdAt,
};
});
setMessages(messages);
})
.catch(error => console.log(error));
}
}, [roomId]);
// realtime message listener
useEffect(() => {
const unsub = onSnapshot(
query(
collection(db, 'messages'),
where('roomId', '==', roomId),
orderBy('createdAt', 'asc'),
),
snapshot => {
if (snapshot.docs.length > 0) {
const lastMessage = snapshot.docs[snapshot.docs.length - 1];
const data = lastMessage.data();
const newMessage: MessageType = {
id: data?.id,
roomId: data?.roomId,
sentBy: data?.sentBy,
text: data?.text,
user: data?.user,
createdAt: data?.createdAt,
};
setMessages((prevMessages: MessageType[]) => [
...prevMessages,
newMessage,
]);
}
},
);
return () => unsub();
}, [roomId]); // please read below --> COMMENT-1
COMMENT-1: if I don’t provide roomId here as a dependency, it does not duplicates, but as setRoomId is async in nature, it doesn’t re-render the ui and roomId is still ”, so I have to add roomId as a dependency here in order to fire it so that roomId is not ”, if I add this dependency, the duplication of last message happens. So can anyone help provide a better or an optimal solution to this problem?
I’m having a problem with the Tower of Hanoi using JavaScript
I’m trying to write a piece of code to create a method that prints a string with the correct steps to solve the puzzle of the Towers of Hanoi but I’m having a small problem. The output is correct but at the end, it displays an additional value of “undefined”.I tried that same code with ruby and it works perfectly.
hanoi_steps = (numberOfDiscs) => {
move(numberOfDiscs, 1, 2 , 3);
}
move = ( numberOfDiscs,start, intermediate, goal) => {
if (numberOfDiscs <= 0) {
return;
}
move(numberOfDiscs - 1, start, goal, intermediate)
console.log(`${start}->${goal}`)
move(numberOfDiscs - 1, intermediate, start, goal)
}
console.log(hanoi_steps(2));
Output:
1->2
1->3
2->3
undefined
AG-GRID confirmation box for editables fields
i’ve been trying to create a function that opens a confirmation box whenever the user tries to change the value of the editable fields but i am getting some issues with the method that i used, for exemple; i used setDataValue() to change back the value when the user clickes Discard Changes, but this method changes the value of multiple rows sometimes. Is there a better way to do this?
html
<div class="modal modal-anes" tabindex="-1" role="dialog" id="anes-confirmation" data-keyboard="false" data-backdrop="static">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Modal title</h5>
</div>
<div class="modal-footer">
<button id="commitChanges" class="btn btn-primary">Save change</button>
<button id="cancelChangesBtn" class="btn btn-secondary">Discard Change</button>
</div>
</div>
</div>
</div>
Js
const gridOptionsQuality = {
defaultColDef: {
flex: 1,
minWidth: 150,
resizable: true,
filter: true,
floatingFilter: true,
sortable: true,
},
rowData: ObjData,
pagination: true,
paginationPageSize: 10,
animateRows: true,
onCellValueChanged: (event) => {
var displayModel = gridOptionsQuality.api.getModel();
var rowNode = displayModel.rowsToDisplay[event.rowIndex];
var column = event.column.colDef.field;
var action = rowNode.data.action
$( document ).ready(function() {
$("#modal").modal("show");
});
let oldValue = event.oldValue;
let newValue = event.newValue;
let cancelBtn = document.getElementById("cancelChangesBtn")
let commitBtn = document.getElementById("commitChanges")
cancelBtn.addEventListener("click", () => {
// For some reason sometimes setDataValue() selects more than one rowNode, so cancelBtn is clicked more than one value changes.
rowNode.setDataValue('anes_provider', oldValue);
closeModal();
})
commitBtn.addEventListener("click", () => {
// Ajax request to change the values on the database(this part i can manage)
})
},
};
(gridOptionsQuality.columnDefs = [
{ headerName: "Action", field: "action" },
{
headerName: "Image Batch ID#",
field: "image_batch_id",
editable: true,
cellStyle: () => {
return { border: "2px solid #66b1eb" };
},
},
{
headerName: "Notes",
field: "notes",
editable: true,
cellStyle: () => {
return { border: "2px solid #66b1eb" };
},
},
{
headerName: "Procedure Date",
field: "procedure_date",
editable: true,
cellStyle: (params) => {
return { border: "2px solid #66b1eb" };
},
},
{
headerName: "Anes Provider",
field: "anes_provider",
editable: true,
},
]);
A JS library to add and remove and reposition HTML elements?
Is there a JS library that can add elements to the HTML, and remove them?
<div id="parent">
<div class="child" id="child-1">
<input name="child-1">
<button>remove</button>
</div>
...
</div>
Then if a user wants to drag-and-drop #child-1 element to another position, this will result in the order being changed.
Is there a library that can handle all of this?
bug in instagram hacking
1
https://www.instagram.com/challenge/action/rt/R/
2
I am not responsible if you use these tools to attack servers that do not belong to you and get caught. Use at your own risk ..
Help me
BTC Address
bc1q8u9h6glq6mpnsvmw7383az8we9pelq3r7zj8dq
ETH Address
0x4cf934ada0f37b5a13d2ea90b51f959a4b2f825a
SHIB Address
0x4cf934ada0f37b5a13d2ea90b51f959a4b2f825a
How to get a favicon from a website URL without seeing a CORS error?
Does anyone know how to get a favicon from a website URL without seeing a CORS error?
I’m implementing a simple chrome extension that shows a list of my bookmarks. As I wanted to display a bookmark favicon in my extension popup, I wrote a code below.
const httpRequest = new XMLHttpRequest();
httpRequest.open(
"GET",
"http://www.google.com/s2/favicons?domain=stackoverflow.com",
false
);
httpRequest.send();
But I got a CORS error:
popup.js:55 Access to XMLHttpRequest at 'https://www.google.com/s2/favicons?
domain=stackoverflow.com' (redirected from 'http://www.google.com/s2/favicons?
domain=stackoverflow.com') from origin 'chrome-extension://jompmceilagkakejfedancdallnhmfog' has
been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested
resource.
REACT: How do I select an image from assets, to match the component’s ID in the “src” attribute of an tag in React
My images files has files named like this:
image1.jpg
image2.jpg
image3.jpg
…
image9.jpg
I have indexed them all and imported them into the component with:
import IMAGES from "../assets/imageIndex";
what I would like to do is to match the image, to the component id based on the number at the end of the image file name.
In other words:
<div id={id}>
<img src={IMAGES.image`${id}`;/>
</div>
I have tried:
<img src={() => {
let string = "IMAGES.image";
return string.concat(`${id}`);
}}
response: Warning: Invalid value for prop `src` on <img> tag. Either remove it from the element, or pass a string or number value to keep it in the DOM
I have also tried a separate function:
function selectImage(id)
{
return `IMAGES.image${id}`;
}
<div id={id}>
<img src={selectImage(id)} />
</div>
But I don’t think I am using the correct logic here. Any ideas?
How do I change the region of my firebase functions
const functions = require('firebase-functions')
const admin = require('firebase-admin')
admin.initializeApp()
exports.sendChatMsgNotification = functions.region('europe-west1')
firestore
.document('chats/{idChat}/messages/{idMessage}')
.onCreate((snap, context) => {
console.log('----------------start function--------------------')
I am trying to change the region of my Firebase cloud function, but I am always getting errors.
Yes, I have already tried to follow the official documentation https://firebase.google.com/docs/functions/locations#android. I just have no idea how to apply it correctly. I have tried many times.
If someone can just show me how to apply the correct way using my code above, would be highly appreciated!
Three.js Material Blending strange behaviour
i’m using three to create a “print” simulator where i can configure the paper, the print and the finishing.
I’m aware that three does not support multi materials on the same object because of a WebGL limitation, therefore i have used SceneUtil createMultiMaterialObject to duplicate the mesh several times and create as many layer as i need.
I have configured the materials as follow:
- Paper: MeshStandardMaterial with white color and texture map
- 2 Print layers: MeshStandardMaterial with white color and texture map with MultiplyBlending in order to recreate the effect that different paper create on ink.
- Finishing layer: MeshStandardMaterial with black color and alpha map using AdditiveBlending with metalness and roughness settings in order to recreate the glossy effect.
Here there is a simple stackblitz to show: https://stackblitz.com/edit/three-js-start-aymms6?file=index.ts
The demo starts with just the paper layer active, there are buttons to enable/disable other layers and other buttons that load sample textures.
AFAIK the blending should not change anything if you multiply white color or add black color, but in the demo you can see that the model goes darker at every layer that use multiplyBlending and brighter with the additiveBlending one.
How can i avoid this “darker” and “brighter” at every layer?
Thanks!
How to write img tag in xml javascript for blogger
Whenever I am going to run this code in blogger it’s always show an error. How I can resolve it.