Passing Multiple parameters as catch them
I'm trying to pass 'slug' in the URL by adding 'id' and 'type'.
Code:
`/${category.slug}?cid=${category._id}&type=${category.type}`
<Route path="/:slug" element={<ProductListPage />} />
URL
http://localhost:3000/Samsung-3whQlbAYpm?cid=61ed050cab3efd275d49efd6&type=store
Problem : However, in the useParam() I received only slug not addition parameters such as 'cid' and 'type'
For example,
let params = useParams();
Its params have only 'slug' value which is 'Samsung-3whQlbAYpm'
How can I get addition value ?
1 answer
-
answered 2022-01-25 09:50
Drew Reese
The
useParams
hook only gets you the defined route params from the path part of the URL. If you want to access the queryString then use theuseSearchParams
hook fromreact-router-dom
.const [searchParams] = useSearchParams(); const cid = searchParams.get("cid"); const type = searchParams.get("type");
If you happen to still be using
react-router-dom
v5 then use thelocation
object to get thesearch
string to be passed to aURLSearchParams
constructor.const { search } = useLocation(); const searchParams = new URLSearchParams(search);
do you know?
how many words do you know
See also questions close to this topic
-
Error message : MongoServerError: bad auth :Authentication failed
What is the reason behind this error? this code I am using to connect to DB.
const uri =`mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASSWORD}@cluster0.xft2s.mongodb.net/myFirstDatabase?retryWrites=true&w=majority`;
-
In Mongo, If a document I'm saving "Prateek" then I don't want on the next create operation even the "prateek" or "praTEEK", etc is saved
//** If I'm adding a new document with the name: "India", then I don't want that the DB allow another name with the name: "INDIA", "india", "indIA", etc. I'm new and learning, help would be great!!**
// Controller
var Dinosaur = require('../models/dinosaurs'); //addDino module.exports.addDino = (req, res) => { var name = req.body.name; var type = req.body.type; var height = req.body.height; var weight = req.body.weight; var Period = req.body.Period; req.checkBody('name', 'Name is required').notEmpty(); var errors = req.validationErrors(); if (errors) return res.status(400).send({ message: 'Name is Required' }); else { let newDino = { name: name, type: type, height: height, weight: weight, Period: Period } Dinosaur.addDino(newDino, (err, result) => { if (err) { if (err.name) return res.status(409).send({ message: name + ' Already Exist' }); else if (err.url) return res.json({ status: false, error: { url: "Url already exist" }, message: err.url }); else return res.json(err, "Server Error"); } else { return res.status(200).send({ message: "Done" }); } }); } }
// Model
var mongoose = require('mongoose'); //dinosaur schema var DinosaurSchema = mongoose.Schema({ name: { type: String, unique: true }, type: { type: String }, height: { type: Number }, weight: { type: Number }, Period: { type: String } }); var Dinosaur = mongoose.model('dinosaur', DinosaurSchema); //add module.exports.addDino = (query, callback) => { Dinosaur.create(query, callback); }
// GetAll, Already Created a new document with the name "Brachiosaurus"
// > Create, a new create with the first letter lower case "brachiosaurus", Don't want it to be pushed.
- i am trying to run the node of ganache but getting this error
-
how to change prettier format for react native
my code formatting prettier didn't works well for react native, i don't understand where to config it but it works well with flutter
from this code
import { View, Text } from 'react-native' import React from 'react' export default function App() { return ( <View> <Text>Apps</Text> </View> ) }
it's formatted to this
import { View, Text } from 'react-native' import React from 'react' export default function App() { return ( < View > < Text > Apps < /Text> < /View> ) }
-
react-router-dom v6 params only numbers
I want add number regex in may param in react-router-dom v6. it work fin in v5 like it:
<Route path="list/:id(\d+)" element={<MyComponent/>} />
but it not work in v6.
-
How can I fixed my problem"FirebaseError: Firebase: Error (auth/invalid-api-key)."
My environment variable is ok. No comas and name mistakes but they given me error like "FirebaseError: Firebase: Error (auth/invalid-api-key)". How can I fixed it. Please Help me...
This my .env file
REACT_APP_apiKey=AIzaSyBWobnhbdeMdNpXXXXXXXXXXXXXXXXXXXX REACT_APP_authDomain=XXXXX.firebaseapp.com REACT_APP_projectId=XXXX REACT_APP_storageBucket=XXXXX.appspot.com REACT_APP_messagingSenderId=4997390XXXXX REACT_APP_appId=1:4997390XXXXX:web:cc7bc80aa1bdb78fXXXXXX REACT_APP_measurementId=G-M1XDXXXXXX
This my firebase config file
const firebaseConfig = { apiKey: process.env.REACT_APP_apiKey, authDomain: process.env.REACT_APP_authDomain, projectId: process.env.REACT_APP_projectId, storageBucket: process.env.REACT_APP_storageBucket, messagingSenderId: process.env.REACT_APP_messagingSenderId, appId: process.env.REACT_APP_appId, measurementId: process.env.REACT_APP_measurementId, }; when I debugging firebaseConfig object console.log(firebaseConfig.apiKey); ==========> undefined console.log(firebaseConfig.authDomain); ==========> undefined console.log(firebaseConfig.projectId); ==========> undefined console.log(firebaseConfig.storageBucket); ==========> undefined console.log(firebaseConfig.measurementId); ==========> undefined console.log(firebaseConfig.appId); ==========> undefined console.log(firebaseConfig.measurementId); ==========> undefined
client side given error this "FirebaseError: Firebase: Error (auth/invalid-api-key)"
-
unable to save to array react state from response from server
Hi I'm trying to save my response.data to my array state of react but it never stores the correct array but when I do a temporary array it works.
Any help would be appreciated, thanks!
const [allstudentlist, setAllStudentlist] = useState([]); await Axios.post(currentUrl, params).then((res) => { // if res.data[0][] // if res data is there then ; if (res.data["error"]) { alert(res.data["error"]); } else { // alert("Register Successful"); // console.log(res.data[0]); console.log(res.data); // works let temp = res.data; setAllStudentlist(...temp); // works console.log(temp); // returns an empty array console.log(allstudentlist); } });
Reponse data
I tried to test as well with a fake api but it looks like there is an issue with setting Arrays at react
I tried to test with codeSandbox as well with a fake API and it does not work
import "./styles.css"; import React, { Component, useState, useEffect } from "react"; import Axios from "axios"; export default function App() { const [array2, setArray] = useState([]); function handleClick() { Axios.get("https://finalspaceapi.com/api/v0/character/?limit=2").then( function (response) { console.log(response.data); setArray(response.data); console.log(array2); } ); } return ( <div className="App"> <h1>Hello CodeSandbox</h1> <h2>Start editing to see some magic happen!</h2> <button onClick={handleClick}></button> </div> ); }
-
How does React hook handle dependency lists when passing objects to child components?
Parent component like this:
function ParentComponent(){ return ( <ChildComponent data={{ x: 1, y: 2 }} /> ) }
Child component like this:
function ChildComponent({ data }){ const [sum, set] = useState(0) useEffect(() => { set(data.x + data.y) }, [data]) return ( <div>{sum}</div> ) }
If it is like the above method, it will cause repeated rendering between subgroups, because the data is always changing. How should I deal with such a scenario?
Of course I know it's possible to cache data in the parent component by
const [data] = useState({ x: 1, y: 2 })
, but I want to know if there is a better solution, if any object parameter is required useState to cache, is this implementation too complicated?In addition, it can also be stored in the child component through
const dataRef = useRef(data)
, but if a value of data changes, it will not be recalculated.Other parameters such as functions and arrays are the same.
What's wrong with my thinking?
-
How do I call react function in js map?
I have the below code, the problem is in the part where I am calling the RemoveProduct function in the map function:
function AddOrder() { const d = new Date(); let text = d.toString(); const [addOrder] = useMutation(queries.ADD_ORDER); const [editUser] = useMutation(queries.EDIT_USER_CART); const [editProduct] = useMutation(queries.EDIT_PRODUCT); function RemoveProduct (x) { let getProd = useQuery(queries.GET_PRODUCTS_BY_ID, { fetchPolicy: "network-only", variables: { _id : x._id }, }); console.log(getProd.quantity) console.log(x.quantity) let a = getProd.quantity - x.quantity console.log(a) editProduct({ variables: { _id : x._id, quantity: a }, }); return null; } const { currentUser } = useContext(AuthContext); if (error) { return <h1> error</h1>; } else if (loading) { return <h1> loading</h1>; } else if (data && getUserOrders.data && currentUser && data.getUser.cart.length > 0) { let newCart = []; let total = 0; for (let i = 0; i < data.getUser.cart.length; i++) { total += data.getUser.cart[i].price * data.getUser.cart[i].quantity; newCart.push({ orderedQuantity: data.getUser.cart[i].quantity, _id: data.getUser.cart[i]._id, name: data.getUser.cart[i].name, image: data.getUser.cart[i].image, price: data.getUser.cart[i].price, }); } newCart.map((x) => RemoveProduct(x)) editUser({ variables: { id: currentUser.uid, cart: [], }, }); } } export default AddOrder;
I get the following error when I run this code:
Uncaught Error: Rendered more hooks than during the previous render.
How can I fix this? I tried to create a separate component for RemoveProducts and call in this function but that did not work either.
-
React Router - History
I have a react app with multiple routes. On one of my routes I only want to render a certain component if the user navigated from a specific route. How do I check the previous path used to get to the current route? Thanks
-
No routes matched location "/login"
all import statements
import React, { useState } from 'react'; import { BrowserRouter as Router, Route, Routes } from 'react-router-dom'; import Dashboard from './components/Dashboard/Dashboard'; import Preferences from './components/Preferences/Preferences'; import Login from './components/Login/Login'; import useToken from "./useToken"; function App() {
token function for blocking pages before logging in
const { token, setToken } = useToken();
login Route
if (!token) { return( <Router> <Routes> <Route path="/login"> <Route index element={<Login setToken={setToken} />} /> </Route> </Routes> </Router> ); }
after login routes return ( <Route path="/dashboard" element={}> <Route path="/preferences" element={}> ); } export default App;
What am i doing wrong ?
-
I am getting an error 404 using nodeJS and express
I'm having an issue with the routes in my project called review. My other routes have no issue so I'm not sure where I went wrong here. I keep getting error 404 in my frontend and in postman. I believe everything is linking to the right information. I go the route
http://localhost:8080/api/review/addReview and get the 404 error
This is my server.js
const express = require("express"); const cors = require("cors"); const dbConfig = require("./app/config/db.config"); const app = express(); var corsOptions = { origin: "http://localhost:8081" }; app.use(cors(corsOptions)); // parse requests of content-type - application/json app.use(express.json()); // parse requests of content-type - application/x-www-form-urlencoded app.use(express.urlencoded({ extended: true })); const db = require("./app/models"); // const Role = db.role; app.use('/uploads', express.static('uploads')); db.mongoose .connect(`mongodb+srv://password@cluster0.gmvao.mongodb.net/shop?retryWrites=true&w=majority`, { useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false }) .then(() => { console.log("Successfully connect to MongoDB."); // initial(); }) .catch(err => { console.error("Connection error", err); process.exit(); }); // routes // require(".app/routes/favourite.routes")(app); require("./app/routes/auth.routes")(app); require("./app/routes/user.routes")(app); app.use('/api/admin', require('./app/routes/admin.routes')); app.use('/api/review', require('./app/routes/review.routes')); // set port, listen for requests const PORT = 8080; app.listen(PORT, () => { console.log(`Server is running on port ${PORT}.`); });
My routes file
const express = require('express'); const router = express.Router(); const {authJwt} = require("../middlewares"); const Review = require("../models/review.model") router.use(function(req, res, next) { res.header( "Access-Control-Allow-Headers", "x-access-token, Origin, Content-Type, Accept" ); next(); }); router.post("/addReview", [authJwt.verifyToken], (req, res) => { const review = new Review(req.body) review.save((err, review) => { if(err) return res.json({success:false, err}) Review.find({'_id': review._id}) .populate('author') .exec((err, result) => { if(err) return res.json({success: false, err}) return res.status(200).json({success: true, result}) }) }) }) module.exports = router ;
My review model file
const mongoose = require('mongoose'); const Review = mongoose.model( "Review", new mongoose.Schema({ prodID: String, productTitle: String, reviewId: String, content: String, author: [ { type: mongoose.Schema.Types.ObjectId, ref: "User", }, ] }) ); module.exports = Review;
-
Mongoose findByIdAndUpdate - not updating selection
I'm following a tutorial with MERN (source code here: https://github.com/Nikhilthadani/Book-Store-With-MERN-Stack/blob/Backend/controllers/books-controller.js)
Everything seems fine with the initial routing (get & post) , until we added a route for updating entries (PUT) in mongoDB.
Here is my function for the PUT
//book-controller.js const updateBook = async (req, res, next) => { const id = req.params.id; const { name, code } = req.body; let book; try { book = await Book.findByIdAndUpdate(id, {new: true}, { name, code, }); book = await book.save(); } catch (err) { console.log(err); } if (!book) { return res.status(404).json({ message: "Unable To Update By this ID" }); } return res.status(200).json({ book }); };
Here is my Schema
// Book.js const mongoose = require('mongoose') const bookSchema = new mongoose.Schema({ name: { type: String, required: true, }, code: { type: Number, required: true, }, }); module.exports = mongoose.model("Book", bookSchema);
When I try to test this function in Postman, the GET request returns the entry that I'm attempting to update just fine.
Confirming database entry with Get
However, after testing PUT, the particular entry I'm trying to update will remain unchanged, despite no output errors
-
Populate fields from dropdown select in React
I am trying to populate a dropdown menu with an array and have it so the selected item from the dropdown populates the next section. But as soon as I add the loop to match the selected item's ID and the array item with the same ID I start getting an error around _id.
I also have it setup so that when you hit this page you index 0 of the array populates the fields. But the problem is when I select the dropdown and choose an item, it does not work until I select 1, then another different item and then after that it seems to catch and things populate correctly. It seems as though the first number of selections do not get the value and do not set the value to the item ID. After a couple of drop down selections it catches and then populates on select as expected but not sure why I have to make a couple of selections, which fail, before it starts working
I'm passing in an object elements, which has an array posts and that is what I'm using to populate the dropdown.
import { useState, useEffect } from 'react'; import { useSelector, useDispatch } from 'react-redux'; import { useNavigate } from 'react-router-dom'; import { toast } from 'react-toastify'; import { Form } from 'react-bootstrap'; function Journal() { const [val, setVal] = useState(''); const [viewPost, setViewPost] = useState({ title: '', subject: '', entry: '', date: '', }); const dispatch = useDispatch(); const navigate = useNavigate(); const { posts, isLoading, isSuccess, isError, message } = useSelector( (state) => state.posts ); const element = JSON.parse(localStorage.getItem('detailedElement')); const myInitPosts = element.posts.map((post) => post); if (!element) { toast.message('No Element found'); } const handleSelected = (e) => { e.preventDefault(); console.log('Selection made'); setVal(e.target.value); console.log('Val ' + val); for (var i = 0; i <= myInitPosts.length; i++) { console.log(i); if (myInitPosts[i]._id === val) { console.log('We got a match!'); const post1 = { title: myInitPosts[i].title, subject: myInitPosts[i].subject, entry: myInitPosts[i].entry, date: new Date(myInitPosts[i].createdAt).toLocaleString('en-US'), }; console.log('Val ' + val); setViewPost(post1); } } }; return ( <> <section className='content mb-4'> <div className='col mb-4'> <div className='card text-left border-primary shadow-lg'> <div className='card-body'> <span className='ml-4 '> <div className='card-text mt-2'> <h4 className='card-title'> Journal: {element.name}</h4> </div> <div> <Form.Select value={val} disabled={element.posts.length === 1} onChange={handleSelected} > {element.posts.map((post) => { const { title, _id } = post; return ( <option key={_id} value={_id}> {post.title} |{' '} {new Date(post.createdAt).toLocaleString('en-US')} </option> ); })} </Form.Select> </div> <div className='mt-2'> <button className='btn btn-danger btn-sm mb-2' type='button' disabled onClick={''} > Delete Post <span className='badge bg-secondary'></span> </button> </div> </span> </div> </div> </div> </section> <section className='content'> <div className='col'> <div className='card text-left border-primary shadow-lg mb-5'> <div className='card-body'> <span className='ml-4 '> {val ? ( <span> <i>Date: {viewPost.date}</i> </span> ) : ( <span> <i> Date:{' '} {new Date(myInitPosts[0].createdAt).toLocaleString( 'en-US' )} </i> </span> )} <div className='mt-2'> <div className='mt-4'> <label htmlFor='subject'> <h5> <b>Title:</b> </h5> </label> <textfield className='mt-2' type='text' name='subject' id='subject' /> {val ? ( <h5>{viewPost.title}</h5> ) : ( <h5>{myInitPosts[0].title}</h5> )} </div> <div className='mt-1'> <label htmlFor='subject'> <h5> <b>Subject:</b> </h5> </label> <textfield className='mt-2' type='text' name='subject' id='subject' /> {val ? ( <h5>{viewPost.subject}</h5> ) : ( <h5>{myInitPosts[0].subject}</h5> )} </div> <div className='mt-4'> {' '} <label htmlFor='entry'> <h5> <b>Entry:</b> </h5> </label> {val ? ( <p> {' '} <div dangerouslySetInnerHTML={{ __html: viewPost.entry }} ></div> </p> ) : ( <div dangerouslySetInnerHTML={{ __html: myInitPosts[0].entry, }} ></div> )} </div> </div> </span> </div> </div> </div> </section> </> ); } export default Journal;