2

How is it possible to use a variable in which we are storing data from mongoDB, in another react component where we can use the data which is fetched from mongoDB and stored in that variable.

Code for file in which data from mongoDB is fetched and stored in a variable named data

import React,{useEffect,useState} from 'react'
import './HeroSection.css'
import axios from 'axios'
import {useHistory} from 'react-router-dom';

function Homefilter() {
const [search, setSearch] = useState('');    
const history = useHistory();
const [data,setData] = useState('')



 const Getsearch = () =>{
   console.log(search)
  axios.get('/searchdata',{params: {search}})
    .then(response => {
    setData(response.data.data)
    console.log(response);  
    history.push('/searchdata')
    })
    .catch(error => {
      console.log(error);
    });
  }
  // useEffect(() => {
  //   Getsearch();
  // }, []);


    return (
      <div class='container-fluid'>
      <div style={{height:'350px',alignItems:'center'}} class="row" id='colu' >
        <div class='col-lg-12 col-md-12 col-sm-12'>
        <div style={{justifyContent:'center',alignContent:'center',alignItems:'center',textAlign:'center'}} >
        <input style={{display:'inline',width:'35rem'}} type="text" name="search" class="form-control" placeholder="Enter keyword to search Vehicle" 
       value={search}
        onChange={(e)=>setSearch(e.target.value)}
        />
        <button onClick={Getsearch} class="btn btn-primary">Search</button> 
        </div>
        </div>
      </div>
      </div>
    )

  
  

    
}

export default Homefilter

Now I Want to use this data variable in another react component so I can display the data stored in data variable

AHMAD IRSHAD
  • 109
  • 1
  • 2
  • 8

1 Answers1

1

You can pass data to the component you are navigating to in following ways:

  1. Through query params: You can pass query params when navigating to another component like this:

    history.push({/searchdata?**yourdatavariable=**${yourdatavalue}})

and get this query param in the navigated component using react-router's useParams() like this:

const { yourdatavariable } = useParams();
  1. Through setting state object in useHistory()'s push function:

You set state object in useHistory()'s push function like this:

this.props.router.push({
  pathname: '/other-page',
  state: {
    id: 7,
    color: 'green'
  }
})

and retrieving it in the navigated component like this:

props.location.state.id or props.location.state.color

This is an example from: Stackoverflow

Daniyal Malik
  • 578
  • 2
  • 6
  • 15