'Reat Js navigate with json object to another page
Below is my code, I am fetching the data from api and on success I am setting the the response of state in set_ProductDetails. I want to pass the response state to different component and different page with the result and bind the data. I am using "react-router-dom": "^5.2.0".
Product_info.jsx
function GetProductDetails(products) {
const history = useHistory();
useEffect(() => {
console.log("render", history.location.state);
}, []);
return (
<>
<div>
<h1>Transaction Info</h1>
</div>
</>
);
}
export default GetProductDetails
Product_query.jsx
function ProductSearch() {
const [product_id, setProduct_id] = useState();
const [product_search, set_ProductSearch] = useState({ product_id: "" });
const [product_deatils, set_ProductDetails] = useState({ product_id: "" });
const history = useHistory();
//Handle the onSubmit
function handleSubmit() {
try {
set_ProductSearch({ address: product_id });
} catch (e) {
alert(e.message);
}
}
function onAPISuccess(data) {
history.push("/product_info/GetProductDetails", { data });
//here render blank screen
}
useEffect(() => {
const fetchData = async (product_id) => {
try {
const resp = await axios.post(
config.SERVER_URL + "/api/getProductInfo/",
product_id
);
set_ProductDetails(resp.data);
onAPISuccess(data)
} catch (err) {
console.error(err);
fetchData(product_search)
.catch(console.error);
}
}, [product_search]);
return (
<>
<div class="input-group mb-3">
<input
type="text"
class="form-control"
aria-describedby="button-addon2"
id="txt_address"
name="address"
placeholder="Address/Tx hash"
onChange={(e) => setProduct_id(e.target.value)}
></input>
<div class="input-group-append" style={{ color: "white" }}>
<button
class="btn btn-outline-success"
type="button"
id="button-addon2"
onClick={() => handleSubmit()}
>
Search
</button>
</div>
</div>
</>
);
}
export default ProductSearch
Home page
export default function Home() {
return (
<>
<main>
<div
className="col-md-12"
style={{
background: "#fff",
backgroundImage: `url(${Image})`,
height: "245px",
}}
>
<Container className="container-sm">
<Row>
<Col xs lg="5" className="justify-content-md-center">
<div>
<ProductSearch></ProductSearch>
</div>
</Col>
</Row>
</Container>
</div>
</main>
<>
)
}
Solution 1:[1]
Do history.push("/your_path",{..object you want to send}). Then in the component where this history.push redirects, access that object by saying history.location.state (this will return the object you passed while redirecting).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Shubham Waje |
