I am using i18n for internationalization.It works well and works for me. But my problem is, lets say ı send a request to backend for create’a user and backend response ‘This user already exist’
I show the error message to user but, how can i handle this error message ? Let’s say user main language is Spanish and all Page rendered with Spanish language but error message is english ? Is there any solution for this ?
Category: javascript
Category Added in a WPeMatico Campaign
Which Speech to Text library will work in Electron.js? [closed]
I want to add Speech to Text capability in my electron.js application.
I tried Web Speech api and P5.speech but none are working in electron.js.
Which library will work in electron.js for speech to text?
white page after validation of a simple login form using basic html/csss/javascript [closed]
i’m learning js, CSS and html and i tried to make a simple login form. Wether i validate my form with the correct password or not it always sends me afterwards on a blank page. I want to stay on the same index.html webpage if the password is wrong after the alert messsage, and i want to go to the maintenance page if it is right. I don’t get why i get a blank page each time. i did put a redirection on my js function.
Heres the repository
https://github.com/Pecranhou/loginform
am i missing something?
occur error when I want to mock an function that return promise
i have an api directory for server communication that using axios:
import axios from "axios";
const API_BASE_URL = "http://localhost:3002";
axios.defaults.withCredentials = true;
const client = axios.create({
baseURL: API_BASE_URL,
headers: {
"Content-Type": "application/json",
},
});
function fetchProjects() {
return client.get("/projects?_embed=tasks");
}
function fetchTasks() {
return client.get("/tasks");
}
function createTask(params) {
return client.post("/tasks", params);
}
function changeStatus(id, params) {
return client.put(`/tasks/${id}`, params);
}
export { fetchProjects, fetchTasks, createTask, changeStatus };
when i wanna mock the “createTask” function that export from this file, i get an error:
task.test.js
import configureMockStore from "redux-mock-store";
import { createTask } from "../../actions/tasks";
import * as api from "../../api";
import thunk from "redux-thunk";
// mock api module
jest.unmock("../../api")
api.createTask = jest.fn(() => Promise.resolve({data : 'foo'}))
// configuration mock store
const middleware = [thunk];
const mockStore = configureMockStore(middleware);
// suite tests
describe("create task action create store<async>", () => {
test("works", async () => {
const expectedActions = [
{ type: "REQUEST_STARTED" },
{
type: "CREATE_TASK_SUCCEED",
payLoad: { task: "foo" },
meta: { analytics: { event: "create_task", data: { id: undefined } } },
},
];
const store = mockStore({
tasks: {
tasks: [],
},
});
await store.dispatch(createTask({}));
expect(store.getActions()).toEqual(expectedActions);
});
});
and the error is:
TypeError: Cannot read properties of undefined (reading 'then')
23 | return (dispatch) => {
24 | dispatch(requestStarted());
> 25 | api
| ^
26 | .createTask({ title, description, status, timer, projectId })
27 | .then((resp) => {
28 | dispatch(createTaskSucceed(resp.data));
it seems the mock function not return a Promsie and I don’t know for what.
when i mock api module with “jest.mock”, it work without any error
React Class Component is not changing with the change of its props
I want to load data dynamically using graphql. Created an HOC to get the params from props.
The props is changing but data is not being loaded with it. Done the same thing to create dynamic product description page and that’s working perfectly.
I am sending the category name dynamically from the NavBar Component:
<div>
{
categories.map((category, index) =>
<Link key={index} to={`/${category.name}`}>{category.name.toUpperCase()}</Link>
)
}
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
Here is the Routing part:
class App extends Component {
render() {
return (
<div>
<ContextProvider>
<Navbar></Navbar>
<Routes>
<Route path='/' element={<All></All>}></Route>
<Route path='/:categoryName' element={<CategoryWiseProducts />}></Route>
<Route path='/cartPage' element={<CartPage></CartPage>}></Route>
<Route path='/productDescription/:id' element={<ProductDescription />}></Route>
</Routes>
</ContextProvider>
</div>
);
}
}
export default App;
This is the component where I want to show products dynamically:
function withParams(Component) {
return props => <Component {...props} params={useParams()} />;
}
class CategoryWiseProducts extends Component {
static contextType = GlobalContext;
constructor(props) {
super(props);
this.state = {
providedData: {},
}
}
getData(category) {
const query = gql`
{
category(input: { title: "${category}" }) {
name
products {
id
name
gallery
prices{
currency{
label
symbol
}
amount
}
inStock
attributes{
id
name
type
items{
displayValue
value
id
}
}
}
}
}
`
request('http://localhost:4000', query)
.then(data => this.setState({ providedData: data.category }, () => {
}))
}
componentDidMount() {
const { categoryName } = this.props.params;
this.getData(categoryName);
console.log("this is props", this.props);
}
render() {
const { providedData } = this.state;
const { name, products } = providedData;
const { openCartOverlay } = this.context;
console.log("this is data:", providedData, typeof providedData);
return (
<div className='container'>
<h1>{name}</h1>
<div className='allProducts'>
{
products?.map(product => <SingleProductCard product={product}></SingleProductCard>)
}
</div>
<SelectAtrributeDrawer></SelectAtrributeDrawer>
<div style={{ display: `${openCartOverlay ? "block" : "none"}` }} className='overlayContainer'>
<CartOverlay></CartOverlay>
</div>
</div>
);
}
}
export default withParams(CategoryWiseProducts);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
Sudoku solver if statement
I am currently working on a little project: a automated Sudoku solver.
I created an option for the user to manually type in a number in one of squares according to the rules of Sudoku. This works perfectly and has been tested many times to make sure of this.
For the last step of this project I made an if statement which looks for the following:
If the user has left one or more squares open, the if statement will find them. Then it will create a random number between 1 and 9 and checks if this number has been used either in the same horizontal row, vertical row or in the same square, according to the rules of Sudoku. I have tried many different forms of this if statement, but none of them seem to work. Perhaps any of you could help me out. The if statement looks like this:
if (document.getElementById(‘File1’).innerHTML.length == 0){
var randomNumber = Math.floor(Math.random() * 9);
if (randomNumber !== square2 && randomNumber !== square3 && randomNumber !== square10 && randomNumber !== square11 && randomNumber !== square12 && randomNumber !== square19 && randomNumber !== square20 && randomNumber !== square21 && randomNumber !== square4 && randomNumber !== square5 && randomNumber !== square6 && randomNumber !== square7 && randomNumber !== square8 && randomNumber !== square9 && randomNumber !== square28 && randomNumber !== square37 && randomNumber !== square46 && randomNumber !== square55 && randomNumber !== square64 && randomNumber !== square73){
document.getElementById('File1').innerHTML = randomNumber;
}
}
File1 represents the first square of the Sudoku board. The other variables such as square5, square8 etc. are basicly the correspoding squares of the Sudoku board, where square8 represents the 8 square on the board counted from left to right.
Is there anyone who could explain why this if statement does not write the random generated number into the first square of the board?
JS Array.push acts in unexpected way
I am experiencing unexpected behaviour of push function.
The problem is with the latest line of code cited below.
export enum non_searchFieldsNames {
language = 'language',
categories = 'categories',
subtitle = 'subtitle',
publishedDate = 'publishedDate',
id = 'id',
}
enum columnsEnum {
title,
authors,
language,
categories,
subtitle,
publishedDate,
}
function toArray(obj: header | contentCategories | sourceFields) {
return Object.entries(obj)
.sort((a, b) => {
return +a - +b;
})
.map(item => item[1]);
}
let sourceFieldsObject: sourceFields = {
[columnsEnum.title]: searchFieldsNames.title,
[columnsEnum.authors]: searchFieldsNames.authors,
[columnsEnum.language]: non_searchFieldsNames.language,
[columnsEnum.categories]: non_searchFieldsNames.categories,
[columnsEnum.subtitle]: non_searchFieldsNames.subtitle,
[columnsEnum.publishedDate]: non_searchFieldsNames.publishedDate,
};
const sourceFieldsArray = toArray(sourceFieldsObject).push(non_searchFieldsNames.id);
The problem is with the latest line of code. The value I do receive here is 7.
When I simplify it like this
const sourceFieldsArray = toArray(sourceFieldsObject)
I receive an array(however, without the value I try to add, of course).
When I split the logic
const sourceFieldsArray = (toArray(sourceFieldsObject));
sourceFieldsArray.push(non_searchFieldsNames.id);
I get what I wanted. Anyway, I would like to have it as one-liner. So, what is my error?
I have tried also
const sourceFieldsArray (toArray(sourceFieldsObject)).push(non_searchFieldsNames.id)
But it does not help.
Calculate maximum Arc radius between 2 angles
Why some websites use placeholder divs instead of video tags?
Instead of directly using the video tag with the poster, I see some sites are using placeholder divs and they put a fake play icon on the div.
There is no video tag inside it. But when users click on the play icon, then they insert the video tag inside the div and video starts playing. Users don’t notice what is happening. Visually there is no difference.
But I’m wondering if this something can be done for optimization. Could this affect speed in a good way?
Javascript MySQL Query Not Executing
When I try to execute this code the USE query executes but the SELECT query does not. When I try to put a console.log inside of them, the USE one logs but the SELECT one does not. There is not even an error. Can someone please help?
Thank you.
(Sorry if this is really easy to solve, I am very new to MySQL.)
const mysqlconnection = mysql.createConnection({
host: "localhost",
user: "admin",
password: "password"
});
mysqlconnection.connect(function (err) {
if (err) {
mysqlconnection.end();
interaction.reply({ content: 'We had a problem with our database. Please try again later.', ephemeral: true });
console.error(err);
} else {
mysqlconnection.query('USE totalmathlinks', function (err) {
if (err) {
mysqlconnection.end();
interaction.reply({ content: 'We had a problem with our database. Please try again later.', ephemeral: true });
console.error(err);
} else {
mysqlconnection.query('SELECT json FROM userrequests WHERE uid = ' + interaction.member.id), function (err, result) {
if (err) {
mysqlconnection.end();
interaction.reply({ content: 'We had a problem with our database. Please try again later.', ephemeral: true });
console.error(err);
} else {
console.log(result);
}
}
}
});
}
});
Indexes of duplicate elements in an array – Javascript
I am new to JavaScript and am trying to create a function that would take an array, and return a new array containing true for duplicate elements in the original array, and false otherwise. Here is the code I wrote:
count = function(arr, item) {
let number = 0
arr.forEach(elem => {
if (elem == item) {
number++
}
})
return number
}
findAllOccurrences = function(arr, target) {
const duplicatesList = arr.filter(elem => {
if (count(arr, elem) > 1) {
return true
} else {
return false
}
})
return duplicatesList
}
console.log(findAllOccurrences([1, 2, 2, 3, 4, 2, 5, 4], 2))
But it gives me duplicate values instead of true/false.
Expected output
[false, true, true, false, true, false, false, true]
Actual output
[ 2, 2, 4, 2, 4 ]
What I want to ask is, how does arr.filter function work?
Getting count of total documents when using aggregation along with skip and limit
How can I get the total count of documents when using the aggregation along with limit and skip like in the following query?
db.Vote.aggregate({
$match: {
tid: "e6d38e1ecd",
"comment.topic": {$exists: 1},
}
},{
$group: {
_id: {
topic: "$comment.topic",
text_sentiment: "$comment.text_sentiment"
},
total: {$sum: 1},
}
},{
$project: {
topic: {
name: "$_id.topic",
occurence: "$total"
},
sentiment: "$_id.text_sentiment"
}
},{
$sort: {"topic.occurence": -1}
}).skip(SKIP).limit(LIMIT)
how to parse nested json by javascript
Here is the sample with my json after JSON.parse().
{
once: {
version: '20.04',
distributor: 'Ubuntu',
cpu_num: 2,
host_name: 'VM-12-3-ubuntu',
user_name: 'root'
},
time: { allsec: 1755353, day: 20},
mem: {
total_mem: 2035212,
used_mem: 572364,
free_mem: 161520,
},
// these [Object] is what i want to parse
cpu: { jiffies: [ [Object], [Object], [Object] ] },
net: [
{ name: 'eth0', rx: [Object], Tx: [Object] }
]
}
How to make these [Object] to be parse ?
How can i update state immutably. react, redux, redux-toolkit
I’m learning redux, and ive a method addPosts to add posts to the list of posts, and I’m doing it like this.
import { createSlice } from "@reduxjs/toolkit";
var initialState = [{ number: 1 }, { number: 2 }, { number: 3 }, { number: 4 }];
export const postsSlice = createSlice({
name: "postsSlice",
initialState,
reducers: {
addPost: (state, action) => {
state = [...state, action.payload];
},
},
});
export const allPosts = (state) => state.posts;
export const { addPost } = postsSlice.actions;
export default postsSlice.reducer;
and using the state like this.
import { addPost, allPosts } from "./postsSlice";
function Posts() {
var posts = useSelector(allPosts);
var dispatch = useDispatch();
return (
<div>
{posts.map((post) => (
<div>{post.number}</div>
))}
{/* add post */}
<button
onClick={() => {
dispatch(addPost({ number: 1 }));
console.log(posts);
}}
>
addpost
</button>
</div>
);
}
export default Posts;
using state.push(action.payload) works somehow, altough the documentation says not use update state like this, and update in an immutable way.
like this state = [...state, action.payload]. it does not update state with this immutable way.
I don’t know what is wrong that i’m doing.
thanks in advance for any help
Command Handler’s file reading doesn’t work
so basically, I have followed a video (from IGP) on how to make a command handler for a bot. and I can’t figure out why it doesn’t work (Tomfoolery is the folder for commands)
client.commands = new Collection();
const commands = fs.readdirSync("./Tomfoolery/").filter(file => file.endsWith(".js"))
for(file of commands) {
const commandName = file.split(".")[0]
const command = require('./Tomfoolery/'+commandName)
client.commands.set(commandName, command)
}
I tried npm rebuild node-sass and npm rebuild node-sass --force and similar stuff, and it still gives me:
Error: ENOENT: no such file or directory, scandir './Tomfoolery/' (even though Tomfoolery IS on the same folder as the bot.js file)

