Here's parent component:
const Page = () => {
const { user } = useAuth();
const router = useRouter();
const [allUsers, setAllUsers] = useState([]);
const [search, useSearch] = useState("");
useEffect(
() => {
if (user !== null && user.isAdmin) {
const token = localStorage.getItem("token");
api
.get("/users", {
headers: {
authorization: `Bearer ${token}`,
},
})
.then((data) => {
setAllUsers(data.data);
})
.catch((error) => {
if (error.message === "Request failed with status code 401") {
const refresh_token = localStorage.getItem("refresh_token");
const refresh = api
.post("/auth/refresh", {
refresh_token,
})
.then((req) => {
if (refresh.data.token && refresh.data.refresh_token) {
localStorage.setItem("token", refresh.data.token);
localStorage.setItem(
"refresh_token",
refresh.data.refresh_token
);
api
.get("/users", {
headers: {
authorization: `Bearer ${refresh.data.token}`,
},
})
.then((req) => {
setAllUsers(req.data);
});
}
})
.catch((error) => {
if (error.message === "Request failed with status code 400") {
if (error.response.data.message
=== "Refresh Token não encontrado."
) {
router.push("/");
}
}
});
}
});
} else if (!user) {
router.push("/404");
} else {
router.push("/auth/login");
}
},
[user, router]
);
useEffect(
() => {
const filterSearch = () => {
if (search === "") return allUsers;
return allUsers.filter((user) => user._id.includes(search));
};
const filtered = filterSearch(search);
setAllUsers(filtered);
},
[search, allUsers],
search
);
const useConsultasPagination = (data, page, rowsPerPage) => {
return useMemo(() => {
return applyPagination(data, page, rowsPerPage);
}, [data, page, rowsPerPage]);
};
const [page, setPage] = useState(0);
const [rowsPerPage, setRowsPerPage] = useState(5);
const keys = useConsultasPagination(allUsers, page, rowsPerPage);
const handlePageChange = useCallback((event, value) => {
setPage(value);
}, []);
const handleRowsPerPageChange = useCallback((event) => {
setRowsPerPage(event.target.value);
}, []);
if (user !== null && user.isAdmin) {
return (
Search | API
Users
);
} else {
router.push("/404");
}
}
And here's search bar's component:
export const UsersSearch = (props) => {
const {
setAllUsers = () => {},
allUsers = [],
search = "",
useSearch = () => {}
} = props;
const { user } = useAuth();
const router = useRouter();
const SetSearch = (value) => {
useSearch(value);
};
const HandleInputChange = (event) => {
console.log('a')
event.preventDefault();
const target = event.target;
const value = target.value;
if (value === "") {
SetSearch("")
} else {
SetSearch(value);
}
};
if (user.isAdmin) {
return (
);
} else {
router.push("/404");
}
};
The problem I'm facing is that, everytime a change the text in the search I get an infinite loop, although the search feature works (and when I remove all the text from the bar it doesn't comes back to the initial allUsers value).
Help me please :)
Changed the useEffect from causing another loop
09 September, 2023
08 September, 2023
Some AWS lamba execution have more than 1 S3event key
Programing Coderfunda
September 08, 2023
No comments
I'm having an issue when passing events to the AWS lambda function.
I have to sync 60k data in 1 json file to a remote server.
My solution is to divide the file into many small files (2000 data/ file) since the function cannot process 60k data in 15 minutes.
After breaking the files, I will upload them one by one to S3 (time interval is 10 seconds), when a new file is uploaded, it will send a S3Event notification to trigger the function, and that function execution will take the newest uploaded file to process.
The speed is impressive, but when the number of data reaches 60k, it does not stop, it continues adding more 4k items (I don't know where it came from).
When I check the newest CloudWatch log, it seems there are some executions that have more than 1 S3Events like below
"Records": [
{
"eventVersion": "2.1",
"eventSource": "aws:s3",
"awsRegion": "ap-southeast-1",
"eventTime": "2023-09-08T06:26:38.873Z",
"eventName": "ObjectCreated:Put",
"userIdentity": {
"principalId": "AWS:AIDA4EODLYGLIMIHEIAVB"
},
"object": {
"key": "test_4.json",
"size": 846900,
"eTag": "44768b0689b2acd120c7683d8f0ce236",
"sequencer": "0064FABE9E323A01CD"
}
}
}
]
"Records": [
{
"eventVersion": "2.1",
"eventSource": "aws:s3",
"awsRegion": "ap-southeast-1",
"eventTime": "2023-09-08T06:28:06.642Z",
"eventName": "ObjectCreated:Put",
"userIdentity": {
"principalId": "AWS:AIDA4EODLYGLIMIHEIAVB"
},
"object": {
"key": "test_12.json",
"size": 845141,
"eTag": "05008d0d12413f98c3aefa101bbbd5eb",
"sequencer": "0064FABEF5B003C033"
}
}
}
]
This is so weird, This is the 1st time I have worked with AWS so can someone help me explain the reason? Also, Is it possible to make all execution run synchronously instead of asynchronously? I think if they are running in order, it will be easily to debug then.
LINQ Query returning an empty result
Programing Coderfunda
September 08, 2023
No comments
I am fairly new to LINQ and am having problems with a query.
var LoadDetentionTypes = _db.Settings_DetentionTypes
.Where(f => SchoolAreaList.Any(s => f.SchoolArea.Equals(s)))
.Select(i => new
{
i.DetailsforDetentionToShow,
i.DetentionTypeDescription,
i.DetentionTypeCode
});
SchoolAreaList is an array and holds say for example two values: BMS and BSS
f.SchoolArea is a column in the database and can hold values in the format ["BMS", "BSS"]
I am trying to do a query that will check if any of the values in the array are in the database and if there is a match it selects the record. The problem is that this query continually returns an empty result. Before using Equals, I used Contains, but I received an error.
Am I trying to do too much in a single line and should I break it up with a ForEach on the array and add to a list?
Any help would be much appreciated.
Regards,
Darren
06 September, 2023
bash: How to check if variable exists when set -eu option is set
Programing Coderfunda
September 06, 2023
No comments
In one of my prod script set -eu is set. In this script I want to check if variable exists but -v and -z option is not working.
#!/bin/bash
set -eu
set -o pipefail
INTERNAL="sdkhf"
if [ -v $IINTERNAL ]
then
echo "variable doesnt exists"
else
echo "variable exists"
fi
output
./script.sh: line 7: IINTERNAL: unbound variable
Is there a way to check for variable if it doesnt exist, dont go inside if loop.
05 September, 2023
How to make C# connect only to an encrypted Access file
Programing Coderfunda
September 05, 2023
No comments
The problem is that it connects to the encrypted file by password, but if you decrypt the Access file, it still connects
I did so, but anyway, if the file "File.accdb" is not encrypted, it connects
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\File.accdb;Jet OLEDB:Encrypt Database = True;Jet OLEDB:Database Password=12345"
Pest Driven Laravel Course is now on Laracasts
Programing Coderfunda
September 05, 2023
No comments
Christoph Rumpel's Pest Driven Laravel course is now live on Laracasts and available to subscribers immediately. Learn about resources that can help get you started with Pest.
The post Pest Driven Laravel Course is now on Laracasts appeared first on Laravel News.
Join the Laravel Newsletter to get Laravel articles like this directly in your inbox.
---
04 September, 2023
How to "copy the Oracle JDBC driver into sonarqube_extensions/jdbc-driver/oracle"?
Programing Coderfunda
September 04, 2023
No comments
I’m setting up Sonarqube according to Install the server and there I see a very strange instruction:
a. Start the SonarQube container with the embedded H2 database:
$ docker run --rm \
-p 9000:9000 \
-v sonarqube_extensions:/opt/sonarqube/extensions \
b. Exit once SonarQube has started properly.
c. Copy the Oracle JDBC driver into sonarqube_extensions/jdbc-driver/oracle.**
Where can I get JDBC driver and how to put it in sonarqube_extensions/jdbc-driver/oracle?
Nothing. I don't know where to get JDBC driver and how to put it in sonarqube_extensions/jdbc-driver/oracle.
Call component method when service's signal updates
Programing Coderfunda
September 04, 2023
No comments
Let me preface this question with the fact that I started learning Angular about a month ago.
Basically, I have a searchbar component and several different itemcontainer components (each of them displays a different type of item). In an attempt to have access to the serchbar value on any component, I created a searchbarService like so:
import { Injectable, signal, WritableSignal } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class SearchBarService {
searchTextSignal: WritableSignal = signal('');
setSearch(text: string): void{
this.searchTextSignal.set(text);
}
}
The searchbar component calls the setSearch method on input submit. So far so good. Now, the problem comes when trying to work with searchTextSignal on the itemcontainter components. I'm trying to use it like this:
import { Component, signal} from '@angular/core';
import { Factura } from 'src/app/interfaces/factura';
import { FacturaService } from 'src/app/services/factura.service'; //gets items from a placeholder array.
import { SearchBarService } from 'src/app/services/search-bar.service';
@Component({
selector: 'vista-facturas',
templateUrl: './vista-facturas.component.html',
styleUrls: ['./vista-facturas.component.css']
})
export class VistaFacturasComponent {
facturasArray: Factura[] = []; // has all items
filteredFacturasArray = signal([]); // has all filtered items, and is the value that I want to get updated when the signal changes.
constructor(private facturaService: FacturaService, public searchBarService: SearchBarService) { }
getFacturas(): void { //initializes the arrays.
this.facturaService.getFacturas().subscribe(facturasReturned => this.facturasArray = facturasReturned);
this.filteredFacturasArray.set(this.facturasArray);
}
filterFacturas(): void{ // this method is likely the problem
let text = this.searchBarService.searchTextSignal();
if (!text)
this.filteredFacturasArray.set(this.facturasArray);
this.filteredFacturasArray.set(this.facturasArray.filter(factura => factura?.numero.toString().includes(text)));
}
ngOnInit(): void {
this.getFacturas();
}
}
The templace uses ngFor like so:
So, everything boils down to how to make VistaFacturasComponent call filterFacturas() when searchBarService.searchTextSignal() updates. Any ideas?
03 September, 2023
originalError: ConnectionError: Login failed for user 'userName' when connecting Node.js to SQL Server
Programing Coderfunda
September 03, 2023
No comments
I am trying to connect Node.js to SQL Server for the first time. I would greatly appreciate some help.
This function makes the connection:
import config from './dbconfig.js';
import mssql from 'mssql';
export async function getUsers() {
try {
let pool = await mssql.connect(config);
let users = await pool.request().query('SELECT * from users');
return users.recordsets;
}
catch (error) {
console.log(error);
}
}
The config I am importing looks like this:
const config = {
user: 'userName',
password: 'password',
server: 'localhost',
database: 'learningProgress',
options: {
trustedconnecion: true,
enableArithAbort: true,
instancename: 'DESKTOP-564IAGD\SQLEXPRESS',
encrypt: true,
trustServerCertificate: true,
}
port:55829
};
export default config;
In place of userName and password I used my Windows user name and password, is that correct?
In place of instancename I used DESKTOP-564IAGD\SQLEXPRESS, is this correct?
How do I know what my port number is? When my port number is part of the config I get this error:
ConnectionError: Failed to connect to localhost:55829 - Could not connect (sequence)
code: 'ESOCKET'
I tried running this SQL command:
SELECT DISTINCT local_net_address, local_tcp_port
FROM sys.dm_exec_connections;
but I got null.
I will mention that my SQL Server browser is running, and TCP/IP is enabled, IP Addresses - TCP port is set to 1433 (all of them).
If I do not have port in the config this is my error regard the userName:
Promise { }
ConnectionError: Login failed for user 'userName'.
code: 'ELOGIN',
isTransient: undefined
}
}
