How to access state from a react function component?

How to access state from a react function component?

Problem Description:

Basically I am using react-router(version 5) to pass data, however I can’t access the state that I passed. Here is the code where it routes from:

export default function MarketsList(props) {
  const history = useHistory();
  function changePage(sym, id) {
    history.push({ pathname: `/${sym}`, state: { id: id } })
  }

how do I access it from the other page? I tried this.state.id but it doesn’t work.
here is the code for the other page just in case.

export default function Symgraph(props) {
  useEffect(() => {

  }, []);
  const { sym} = useParams();
  return (
    <div className='main-chart mb15' >
      <ThemeConsumer>
        {({ data }) => {
          return data.theme === 'light' ? (
            <AdvancedChart
              widgetProps={{
                theme: 'light',
                symbol: 'OKBUSDT',
                allow_symbol_change: false,
                toolbar_bg: '#fff',
                height: 550,
                details: 'true',
                style: '3',
              }}
            />
          ) : (
            <AdvancedChart
              widgetProps={{
                theme: 'dark',
                symbol: 'OKBUSDT',
                allow_symbol_change: false,
                toolbar_bg: '#000',
                height: 550,
                details: 'true',
                style: '3',
              }}
            />
          );
        }}
      </ThemeConsumer>

      <h1>{sym},{this.state.id}</h1>
    </div>
  )
}

Solution – 1

I think you need to use useHistory for it

sth like this:

  let history = useHistory();

history.location?.state?.id

Solution – 2

import { useHistory, useLocation } from 'react-router';
const Component = ()=>{
 const location = useLocation();
 console.log(location.state.id);  // here you can access id;
}
Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.
Accept
Reject