ReactJS | Getting data from URL returns null - reactjs

I am sending a form data from a form in reactjs. Some pre inputs from the user have to be sent altogether with the form. I get that data from the URL of the parent file and the form is in the child component.
Parent url: http://localhost:3000/uploadlist?phmcy=2
I have to get the phmcy value from the URL. (Here the data have to be passed is '2').
But the phamcy value returns "null" And I tried everything I knew but it keeps returning the null value.
The code segment of the parent file:
import Upload from './Upload'
import axios from "axios";
import { Link, withRouter } from "react-router-dom";
import { useLocation } from 'react-router';
export default function Uploadlist() {
let myphmcy = (new URLSearchParams(window.location.search)).get("phmcy.value")
console.log(myphmcy);
//rest of the code is not added.
Can someone please help me with this issue?

Correct me if I'm wrong, I think you are trying to get the value inside phmcy, right?
Change the get state meant to the following:
let myphmcy = (new URLSearchParams(window.location.search)).get("phmcy").value

Try this:
import Upload from './Upload'
import axios from "axios";
import { Link, withRouter } from "react-router-dom";
import { useLocation } from 'react-router';
import { useEffect } from "react";
export default function Uploadlist() {
const { search } = useLocation();
useEffect(() => {
const phmcy = new URLSearchParams(search).get("phmcy");
console.log(phmcy);
}
}

Related

How to show data in realtime database firebase in react js

import React, { useState ,useEffect} from 'react';
import { Link ,useHistory,useParams} from 'react-router-dom';
import { getDatabase,ref, child, get } from 'firebase/database';
import { auth, db } from './Config/Config';
export default function User()
const [user,setUser]=useState()
const {id}=useParams();
const dbRef = ref(getDatabase());
get(child(dbRef, AllUsers/${id})).then((snapshot) => {
if (snapshot.exists()) {
setUser(...snapshot.val());
} else {
console.log('user',user)
return (
{id}
</div>
)
}
IDK how to use that firebase id tho but if want to show data getting as responses then you already store firebase data in the local-state now you can use that state to get data and show anywhere {user.id} or whatever ur getting in response!
It's a design pattern using lowercase as params. So rename to allusers or all-users.
Are you sure you getting the right ID from params ?
also, paste your full code pls.

why useState() is not working in react js?

when I declare a use State variable, my react app stops working.. if I uncomment the useState then the code works fine. I don't understand what is the problem?
import React from "react";
import { Helmet } from "react-helmet";
import { Link } from "react-router-dom";
import useState from "react";
import "./login.scss";
const Login = (props) => {
const [credentials, setCredentials] = useState({
user_name: '',
password: '',
})
return (
<div className="application">
</div>
);
}
export default Login;
There could be a few things wrong here:
Are you importing useState from react?
import React, { useState } from "react"
Are you setting value using setText or setting a default state value? Your current example sets default state for text as ''
Are you returning text in the render method? E.g.
return <p>{text}</p>
Are you using React v16.8 or greater? If not hooks will not be available
put curly braces around useState where you imported it like so..
import { useState } from "react";
other than that everything looks fine!
you can potentially delete the line with
import React from "react";
but it's not gonna change anything :)
Instead of:
import useState from "react";
Write:
import { useState } from "react";
Why do I need to add { } to the import?
Answer: When using import on something that was exported with the default keyword - you don't need to wrap the variable name in { }.
However, when using import on something that was exported not as default, you are required to wrap the variable name with { } and say exactly what you want to import.

How to extract an URL segment in React

I have inherited a project and are very new to React.
The problem is that I don't know how to extract an URL segment like 123456 from the URL page/123456.
Here is some code for I sidebar I want to use the URL segment in. I kept it short so it is as clear as possible where I want the URL segment.
import React, { Component } from 'react';
import { withRouter, Link } from 'react-router-dom';
import { compose } from 'redux';
import { connect } from 'react-redux';
import { push } from 'connected-react-router';
class Sidebar extends Component {
constructor(props) {
super(props);
this.state = {};
}
render() {
return (
<div>
URL segment:
</div>
);
}
}
export default compose(withRouter))(Sidebar);
If you have a router configured properly then you might be able to find that value as a string in the this.props.match.params. You can take a look to the following example(please note that it's using react hooks and the main difference for you would be to use this.props.match.params instead of useParams()).
P.S. you should call withRouter instead of passing it to the compose method. E.g. withRouter(Sidebar) and if you want to use it with connect I guess you can just call one inside the other: connect(...)(withRouter(Sidebar))

How to retrieve the parameter after a hash (#) with React Router and useParams hook?

I have a route like
<Route path="/search/:slug"><SearchPage /></Route>
in my React Router. SearchPage is a component that uses the useParams() hook provided by react-router-dom.
// SearchPage.js
import React from 'react';
import { useParams } from 'react-router-dom';
export function SearchPage(props) {
const { slug } = useParams();
console.log(slug)
// ...do other stuff
}
However, when I navigate to /search/foo#bar, the SearchPage component only receives foo in the slug. It is possible for my component to receive the full foo#bar, or, better yet, foo and bar separately?
You need to use useLocation hook and get the hash from there. First step is to import useLocation from react-router-dom:
import useLocation from "react-router-dom";
Inside the component function, use this:
const { hash } = useLocation();
From the docs:
useLocation
The useLocation hook returns the location object that represents the current URL. You can think about it like a useState that returns a new location whenever the URL changes.
This could be really useful e.g. in a situation where you would like to trigger a new “page view” event using your web analytics tool whenever a new page loads
In a URL like this: "/myUrl/products/product12?myQuery=12#myHash"
The UseParams will return everything up to the query e.g "/myUrl/products/product12" but not the query "?myQuery=12#myHash".
React has a hook for this "useLocation". Use Location will give you an object with 4 things but only 3 that you need to worry about for this example, (
"pathname": "/myUrl/products/product12",
"search": "myQuery=12",
"hash": "myHash")
import { useLocation } from 'react-router-dom';
const QueryDetails = () => {
const location = useLocation();
const myQuery = location.search;
return (
<div className='container mt-2'>
<p>{myQuery}</p>
</div>
);
}
export default QueryDetails;

How to use history.push in HOC reactjs?

I am having an axios intercept . It will catch every request . My idea is to dispatch errors commonly in the same place. So i created this intercept. If 404 error came means i will dispatch an action and redirect the page to home. But unfortunately i cant access the props.history in HOC.
Here i am sharing the code of what i have implemented:
HOC axios intercept:
import React, {useEffect} from "react";
import axios from "axios";
const checkRequests= Wrapped => {
function CheckRequests(props) {
useEffect(()=>{
axios.interceptors.response.use(function (response) {
// Do something with response data
return response;
}, function (error) {
switch (error.response.status) {
case 404 :
props.history.push('/login') // will redirect user to login page
break
default :
break
}
// Do something with response error
return Promise.reject(error);
});
})
return (
<Wrapped {...props} />
)
}
return CheckRequests
}
export default checkRequests
And wrapping this component in App.js:
import React from "react"
import CheckRequests from "./HOC/CheckRequests"
function App(props){ ... }
export default checkRequests(App)
Error:
When is console the props in HOC it comes empty
console.log(props) => {}
Please help me with that. Is there any other way to access the history.push from that HOC. For disptaching an action an action am using store.dispatch(logout()).
Wrap the withRouter HOC in the export statement like this:
export default withRouter(checkRequests);
Don't forget to import at the top of the file
import { withRouter } from "react-router";
You may use withRouter
import { withRouter } from 'react-router-dom';
export default withRouter(checkRequests);
Thanks for your answer. I added your suggestion into my code. But i got this error You should not use Route or withRouter() outside a Router . Then i found that it is outside the router so i added this
import { BrowserRouter } from 'react-router-dom';
ReactDOM.render(
<BrowserRouter>
<App />
</BrowserRouter>
, document.getElementById('root'));
on the index.js . It works fine.

Resources