I’m currently using “react-router-dom”: “^5.2.0”, with “history”: “^4.10.1”. It should be working with these versions, but the redirect won’t render the page.
Category: javascript
Category Added in a WPeMatico Campaign
TypeError: Prismic.getApi is not a function
i’m really struggling while trying to build a website from scratch without a framework. And now i’m integrating Prismic in through node.js, but as I’m following all the passages i’m getting stuck by this error shown in the log of the terminal: TypeError: Prismic.getApi is not a function.
As a consequence of this i can see the local website but the about link doesn’t load. How can i fix that?
This is the main code related to the package.json
require('dotenv').config()
console.log(process.env.PRISMIC_ENDPOINT, process.env.PRISMIC_CLIENT_ID)
const express = require('express')
const app = express()
const path = require('path')
const port = 3000
const Prismic = require('@prismicio/client')
const PrismicDOM = require('prismic-dom')
const initApi = req => {
return Prismic.getApi(process.env.PRISMIC_ENDPOINT, {
accessToken: process.env.PRISMIC_ACCESS_TOKEN,
req
})
}
const handlelinkResolver = doc => {
// Define the url depending on the document type
// if (doc.type === 'page'){
// return '/page/' + doc.uid;
// } else if (doc.type === 'blog_post'){
// return '/blog/' + doc.uid;
// }
// Default to homepage
return '/'
}
app.use((req, res, next) => {
res.locals.ctx = {
endpoint: process.env.PRISMIC_ENDPOINT,
linkResolver: handlelinkResolver
}
res.locals.PrismicDOM = PrismicDOM
next()
})
app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'pug')
app.get('/', async (req, res) => {
res.render('pages/home')
})
app.get('/about', async (req, res) => {
initApi(req).then((api) => {
api.query(
Prismic.Predicates.at('document.type', 'about')
).then(response => {
console.log(response)
res.render('pages/about')
})
})
})
app.get('/personaggi', (req, res) => {
res.render('pages/personaggi')
})
app.get('/detail/:uid', (req, res) => {
res.render('pages/detail')
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
material ui table delete function not working
why is my code showing wrong output for
as the rows has been already populated after adding it with the handletabledata function
My code is having a table and there is a add button where we add users but on the delete function when I am trying to see the rows I am getting only that row and rows above it.
please help.
import React from 'react'
import './server.scss'
import Paper from '@mui/material/Paper';
import Table from '@mui/material/Table';
import TableBody from '@mui/material/TableBody';
import TableCell from '@mui/material/TableCell';
import TableContainer from '@mui/material/TableContainer';
import TableHead from '@mui/material/TableHead';
import TablePagination from '@mui/material/TablePagination';
import TableRow from '@mui/material/TableRow';
import { Button } from '@mui/material';
import DeleteOutlineIcon from '@mui/icons-material/DeleteOutline';
import Dialog from '@mui/material/Dialog';
import DialogActions from '@mui/material/DialogActions';
import DialogContent from '@mui/material/DialogContent';
import DialogContentText from '@mui/material/DialogContentText';
import DialogTitle from '@mui/material/DialogTitle';
import Slide from '@mui/material/Slide';
import PersonAddAltIcon from '@mui/icons-material/PersonAddAlt';
import TextField from '@mui/material/TextField';
import InputLabel from '@mui/material/InputLabel';
import MenuItem from '@mui/material/MenuItem';
import FormControl from '@mui/material/FormControl';
import Select from '@mui/material/Select';
const columns = [
{ id: 'key', label: '#', minWidth: 70 },
{ id: 'user', label: 'User', minWidth: 100 },
{
id: 'signed',
label: 'Last Signed in',
minWidth: 170,
align: 'right',
},
{
id: 'role',
label: 'Role',
minWidth: 170,
align: 'right',
},
{
id: 'icon',
label: '',
minWidth: 170,
align: 'right',
},
];
function createData(user, role, key, icon, signed) {
signed = signed.getTime()
return { key, user, signed, role, icon };
}
//modal code
const Transition = React.forwardRef(function Transition(props, ref) {
return <Slide direction="up" ref={ref} {...props} />;
});
const Server = () => {
//final insertion of data
const [rows, setrow] = React.useState([]);
// console.log(rows)
//pagination
const [page, setPage] = React.useState(0);
const [rowsPerPage, setRowsPerPage] = React.useState(10);
const handleChangePage = (event, newPage) => {
setPage(newPage);
};
const handleChangeRowsPerPage = (event) => {
setRowsPerPage(+event.target.value);
setPage(0);
};
//modal code
const [open, setOpen] = React.useState(false);
const handleClickOpen = () => {
setOpen(true);
};
const handleClose = () => {
setOpen(false);
};
//setting data for row
const [id, setid] = React.useState(0);
const handletabledata = () => {
setid(id + 1)
let row = [...rows]
row.push(createData(email, role, id, <DeleteOutlineIcon onClick={console.log(rows)}/>, new Date()))
setrow(row)
setemail('')
setrole('')
setOpen(false);
}
//input field
const [email, setemail] = React.useState('');
const handleEmail = (event) => {
setemail(event.target.value);
};
//dropdown list
const [role, setrole] = React.useState('');
const handleChange = (event) => {
setrole(event.target.value);
};
return (
<div className='server_main'>
<div className='addUser'>
<Button variant="contained" onClick={handleClickOpen}>Add User</Button>
<Dialog
open={open}
TransitionComponent={Transition}
keepMounted
onClose={handleClose}
aria-describedby="alert-dialog-slide-description"
fullWidth={true}
>
<DialogTitle>{"Add User"}</DialogTitle>
<DialogContent>
<DialogContentText id="alert-dialog-slide-description">
<div style={{ display: 'flex', height: '250px', justifyContent: 'space-around' }}>
<div >
<PersonAddAltIcon style={{ fontSize: '7rem', position: 'relative', top: '50px' }} />
</div>
<div style={{ display: 'flex', flexDirection: 'column', justifyContent: 'space-around' }}>
<span style={{ padding: '10px', position: 'relative', left: '10px', top: '10px' }}>User Information</span>
<TextField placeholder="Email Address" onChange={handleEmail} value={email} />
<FormControl fullWidth>
<InputLabel id="demo-simple-select-label">Role</InputLabel>
<Select
labelId="demo-simple-select-label"
id="demo-simple-select"
value={role}
label="role"
onChange={handleChange}
>
<MenuItem value={'Owner'}>Owner</MenuItem>
<MenuItem value={'Sales'}>Sales</MenuItem>
<MenuItem value={'Admin'}>Admin</MenuItem>
</Select>
</FormControl>
</div>
</div>
</DialogContentText>
</DialogContent>
<DialogActions>
<Button onClick={handleClose}>Cancel</Button>
<Button onClick={handletabledata}>Add</Button>
</DialogActions>
</Dialog>
</div>
<Paper sx={{ width: '100%', overflow: 'hidden' }}>
<TableContainer sx={{ maxHeight: 440 }}>
<Table stickyHeader aria-label="sticky table">
<TableHead>
<TableRow>
{columns.map((column) => (
<TableCell
key={column.id}
align={column.align}
style={{ minWidth: column.minWidth }}
>
{column.label}
</TableCell>
))}
</TableRow>
</TableHead>
<TableBody>
{rows
.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage)
.map((row) => {
return (
<TableRow hover role="checkbox" tabIndex={-1} key={row.code}>
{columns.map((column) => {
const value = row[column.id];
return (
<TableCell key={column.id} align={column.align}>
{column.format && typeof value === 'number'
? column.format(value)
: value}
</TableCell>
);
})}
</TableRow>
);
})}
</TableBody>
</Table>
</TableContainer>
<TablePagination
rowsPerPageOptions={[10, 25, 100]}
component="div"
count={rows.length}
rowsPerPage={rowsPerPage}
page={page}
onPageChange={handleChangePage}
onRowsPerPageChange={handleChangeRowsPerPage}
/>
</Paper>
</div>
);
}
export default Server
how do i write SQL Query for getting following output from two tables (With Nodejs)
table 1:
teacher
+------+--------------+
| id | Teacher_name |
+------+--------------+
| 1 | M |
| 2 | S |
+------+--------------+
table 2:
Students
+------+--------------+
| id | Subject_name |
+------+--------------+
| 1 | English |
| 1 | Marathi |
| 1 | Hindi |
| 2 | Biology |
| 2 | Physics |
| 2 | History |
+------+--------------+
i need output like
[
{
"Teacher_name": "M",
"Subjects": [
{
"Subject_name": "english"
},
{
"Subject_name": "marathi"
},
{
"Subject_name": "hindi"
}
]
},
{
"Teacher_name": "S",
"Subjects": [
{
"Subject_name": "biology"
},
{
"Subject_name": "physics"
},
{
"Subject_name": "history"
}
]
}
]
Unable to deploy react application to heroku
so I just finished building the beta version of my e-commerce application and decided to deploy to heroku from my github repository.
The first issue I ran into was not npm run build (which I did then pushed it to github) then redeployed.
Next issue was my build failed because I didn’t specify the version of node. (SO i want into the package.json and typed in…)
“engines”: {
“node”: “16.14.2”
},
Again, redeployed I got through the build and I thought all was well. BUT I get an application error (fun) and so I go into heroku logs to see what I did wrong. Problem is I actually don’t know what i did wrong. This is what the log says
Ext JS 7.0: Get responded JSON string from router
I wrote an Ext JS 7.0 app with a grid that uses Ext Direct to connect to a SQL database based on the example by Sencha (https://docs.sencha.com/extjs/7.0.0/guides/backend_connectors/direct/mysql_php.html). This works fine.
The app has also some views with a few textfields. Their content is stored in the database, too, but in a different table, so I added the necessary functions to QueryDatabase.php and extended config.php. Now writing into the database works by simply calling the corresponding (php) function in the controller, e. g. QueryDatabase.updateSettings(JSONstring);.
I also want to initially populate the textfields with the data stored in the database and this is where I get into trouble.
If I call the proper read function and assign it to a variable, e. g. settingsJSON = QueryDatabase.getSettings();, settingsJSON stays undefined, although I can see in the browser that router.php returns the correct result (like "{"Setting1":"a value","Setting2":"another value"}").
Since the request is asynchronous, I tried to use a callback function (according to https://docs.sencha.com/extjs/7.0.0/classic/Ext.direct.RemotingProvider.html#cfg-actions):
onSettingsRefreshClick: function() {
console.log('Hello world!');
QueryDatabase.getSettings(function(result, e, success, options) {
console.log('Hello again!');
var t, action, method;
t = e.getTransaction();
action = t.action;
method = t.method;
if (e.status) {
console.log(Ext.encode(result));
}
})
}
But this isn’t working either. router.php still delivers the correct result, but it isn’t shown in the console. Obviously the whole callback function isn’t executed as ‘Hello again!’ also doesnt’t appear in the console (‘Hello world!’ does). So how do I assign the JSON string returned by router.php to a variable?
Double sort list in react-native
I’d like to know how to “double sort” items in react native in order to obtain a double criteria sorted list.
The data I receive from BE is a list of match: every match is an object containing 2 players, a time and a competition.
I d’like to sort items by time (so that a today match is showed before a tomorrow match) and by competition (so that a more important competition is showed before a lower one).
If two or more matches are played on the same day and within the same competition, the earlier match is showed before.
A schema better shows what I mean: I’d like to customize the UI oc the day-row, the competition-row and the match-row.
The data I receive from BE are formatted in this way:
How could I obtain what I want? I’ve tried with sortable list but with no result.
TY in advance
Track the login event with Google Analytics in a WordPress website
I wish to track when a user log in their account in my WordPress website with GA4 (Google Analytics 4), so I used the hook ‘wp_login’, as you can see in the snippet below that I added to functions.php file, but it doesn’t work. I tried the hook alone (to create a cookie) and it works fine and I tried the code inside the function ‘gal’ alone and it works fine.
add_action('wp_login', 'gal',90);
function gal(){
echo "<script>dataLayer.push({event: 'login'});</script>";
}
HTML/JAVASCRIPT ondragleave fired when moving between child objects
I have a problem with the behaviour of the javascript ‘ondragleave’ that is fired between child elements.
See the example with some simple code.
The problem is that the records would not stay red between the two TD elements, although the mouse is still dragging in the TR record.
There are some answers that include counters, but non of them seems to make is possible to work
function enter(ev, recordid) {
document.getElementById(recordid).style.backgroundColor = '#AA0000';
}
function leave(ev, recordid) {
document.getElementById(recordid).style.backgroundColor = '';
}
<p draggable="true" id="dragtarget">Drag me!</p>
<table width=100% style='border-spacing: 30px;'>
<tr id='record1' ondragenter='enter(event, this.id);' ondragleave='leave(event, this.id);'>
<td>Record 1-1</td>
<td>Record 1-2</td>
<td>Record 1-3</td>
<td>Record 1-4</td>
</tr>
<tr id='record2' ondragenter='enter(event, this.id);' ondragleave='leave(event, this.id);'>
<td>Record 2-1</td>
<td>Record 3-2</td>
<td>Record 4-3</td>
<td>Record 5-4</td>
</tr>
</table>
Setting an state with an array variable cannot add a new property Error
I am using Geolocation service and pushed coordinate changes in to an array variable but when I use set state it throws an error it says cannot add new property.
here is my code :
let dataarray = []
const startTrackingFunction = async () => {
await Geolocation.watchPosition(
position => {
const crd = position.coords;
setPosition({
latitude: crd.latitude,
longitude: crd.longitude,
latitudeDelta: LATITUDE_DELTA,
longitudeDelta: LONGITUDE_DELTA,
});
dataarray.push(crd);
setCoordinates(dataarray);
},
error => {
console.log(error);
},
{
showLocationDialog: true,
enableHighAccuracy: true,
timeout: 20000,
maximumAge: 0,
distanceFilter: 0,
});
setTracking(true);
}
<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>
CSS SVG background-image as data-uri: is there a way to access ids/classes in that SVG with ‘external’ CSS
I have a website / application that uses different color themes.
Those themes are provided in css-custom-properties:
like:
:root{
--main-color: red;
--lighht-color: gray;
--dark-color: brown;
...
}
those are abstracted for flexibility like:
:root{
--main-text-color: var(--dark-color);
....
}
Now I have check-boxes that should use SVG-Background uri-s like this:
input[type=checkbox]:checked{
--check-color: blue;
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100' style='enable-background:new 0 0 100 100' xml:space='preserve'%3E%3Cstyle type='text/css'%3E%0A%23check%7B%0Astroke: var(--check-color);%0A%7D%0A%3C/style%3E%3Cpath id='check' style='fill:none;stroke-width:18;stroke-miterlimit:10' d='m24.3 36.8 20.9 29.3 45.7-41.8'/%3E%3C/svg%3E");
stroke: red !important;
}
you can already see that I tried to change the color of the check-mark from outside the uri-string in several ways without success.
I also tried:
:root{
stroke: green;
--check-color: lime;
}
and
#check{
stroke: pink;
}
with no success.
I did a lot of research and found out that all of those methods will not work, ass the svg in the data-uri is essentially treated as an independent document/dom-sructure form the main document that the is CSS used in…
I can think of three other ways to work around my problem:
CSS-masking: Will likely work, but my actual situation is more complex than the outline I give here and having more than one svg-element to reveal ideally more than one color will be very tricky and complicated.
SASS: If there is a (not overly complex) way to read the value of a css-custom property like root.var(–check-color) into sass and compile it literally into the CSS (inside the svg-uri), that would be helpfully while not ideal; (The opposite of –my-var: #{$sassVar} so to speak). I couldn’t find an opening in to that avenue yet, and with the flexible scoping of css-custom-properties (and them being nested) I guess it will be not easy.
JavaScript / DOM: I could go about to inject spans with SVG-Code into the document, but for reasons of accessibility / clear semantics and validity of my html I don’t like this at all.
I could also try to read the uri via CSSStyleDeclaration and get the Property, replace the color inside the string and set it back. I guess.
That would probably require to
- check an uncheck a box to get the declaration (not wanting to rely on
a fixed way of it being coded in css) - replace a very common string
like ‘#000’ or ‘black’ in a more or less complex string. (I wouldn’t
want to put a ‘$!her-goes-color!$’ the svg, as that would break it if
not replaced…) - deal with url-encoding and -decoding and
- would have to adjust that script with any style and/or graphic update…
Not ideal at all.
But as most times I’m confident that some of you great and knowledgeable people might have an inspiration or solution for me.
THX!
Neo4j CREATE 2022+ syntax Node.js
What is the currently acceptable syntax for sending a CREATE script from Node.js to Neo4j in 2022 and after?
I am getting several errors trying to pass in dynamic props from form input fields.
I need to create a new record from my form inputs using Node.js.
This is an example of a syntax that is no longer accepted:
app.post('/books/add', function(req, res){
var title = req.body.title;
var year = req.body.year;
session
.run('CREATE(n:Book {title: {paramTitle}, year: {paramYear}}) RETURN n:title', {paramTitle:title, paramYear:year})
.then(
function(result){
res.redirect('/');
session.close();
}
)
.catch(function(error){
console.log(error)
});
res.redirect('/');
});
convert if condition to be in excel if function formula in javascript
how to convert an if condition to be in excel if function condition formula in JavaScript.
given formula:
if(0.30864197530864196 >= 15.0 && 0.30864197530864196 < 16.0, 1, 0)
desired formula:
if(AND(0.30864197530864196 >= 15.0, 0.30864197530864196 < 16.0), 1, 0)
I want to convert it to the desired formula to evaluate it using hot-formula-parser in node.js
async onClick with multiple setStates not working as expected
BACKGROUND
I have a object that I am referencing to toggle state changes in an onClick event.
const map = {
active: {
name: "sliceA",
toggle: (map) => map.inactive
},
inactive: {
name: "sliceB",
toggle: (map) => map.active
}
}
useState of component either holds map.acive or map.inactive slice of object via a transition function.
const [slice, setSlice] = useState(map.active);
const transition = (getMethod) => {
const getNewSlice = getMethod(slice);
const result = getNewSlice(map);
setSlice(result);
};
This works as I expect until you attempt multiple state changes in a single onClick event.
const handleClick = async () => {
try {
transition((status) => status.toggle);
await stall();
transition((status) => status.toggle);
} catch (err) {}
};
ISSUE
See link – codesandbox1
If you click button X1 the 2nd transition() in handleClick() will not trigger state change.
If you click button X2 the 2nd transition() in handleClick() will trigger state change.
REQUEST
Why is this happening and is there a way to fix? I made another more manual way of setting state and it operates as expected – codesandbox2
Is there an easy way to show divs by default, then filter/hide on click?
I’m looking for simple and seo/semantic way to filter and sort some content.
Initially all content should be shown, then on click the content should be filtered and only the selected group show.
I’m starting out with the code below as my base. Using widgets as example. Each widget is in its own div containing information about that widget.
Currently the default is to hide all, I’d prefer to show all to be default (I’m not sure why the very first one is showing alone on load.
Is there a way to do it without initially using display:none for the divs, my understanding is this might not be seo friendly.
$('.tab-link').click(function() {
var contClass = $(this).data('div');
$('.result-content').hide().filter('.' + contClass).show()
})
.result-content {
display: none
}
.result-content:first-of-type {
display: block
}
a {
display: inline-block;
margin-right: 10px;
padding: 5px 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<a href="#" class="tab-link" data-div="widgets">All widgets</a>
<a href="#" class="tab-link" data-div="green-widgets">Green</a>
<a href="#" class="tab-link" data-div="red-widgets">Red</a>
<a href="#" class="tab-link" data-div="blue-widgets">Blue</a>
<div class="widgets green-widgets result-content">
Widget 654
</div>
<div class="widgets green-widgets result-content">
Widget 989
</div>
<div class="widgets green-widgets result-content">
Widget 345
</div>
<div class="widgets red-widgets result-content">
Widget 563
</div>
<div class="widgets red-widgets result-content">
Widget 867
</div>
<div class="widgets blue-widgets result-content">
Widget 994
</div>
<div class="widgets blue-widgets result-content">
Widget 924
</div>
<div class="widgets blue-widgets result-content">
Widget 114
</div>



