I have this component, where im trying to trigger the useEffect, which should be triggered when the location changes.
const ChartContainer: React.FC<RouteComponentProps> = ({ history }) => {
const location = useLocation();
const { data, serverError } = useFetchChart(location.search);
const isData = Array.isArray(data) && data?.length > 0;
React.useEffect(() => {
console.log('search');
}, [location]);
if (serverError) {
history.push('/error');
}
if (isData) {
return (
<>
<IntervalSelector />
<Chart dataProp={convertData(data)} />
</>
);
}
return <Spinner />;
};
export default ChartContainer;
THe intervalSelector, allows me to change the queryparam
It looks like:
import React, { useEffect, useState } from 'react';
export const IntervalSelector = () => {
const [selectedValue, setSelectedValue] = useState<string>('1d');
const options = [
'1m',
'5m',
'15m',
'1h',
'4h',
'12h',
'1d',
'3d',
'1w'
];
useEffect(() => {
const searchParams = new URLSearchParams(window.location.search);
selectedValue && searchParams.set('interval', selectedValue);
window.history.replaceState({}, '', `${window.location.pathname}?${searchParams}`);
}, [selectedValue]);
return (
<>
<select
style={{
position: 'absolute',
left: 0,
top: 0
}}
value={selectedValue || ''}
onChange={(e) => {
setSelectedValue(e.target.value);
}}
>
{options.map((option) => (
<option key={option} value={option}>
{option}
</option>
))}
</select>
</>
);
};
So whenever i select "3d" for example, my url changes from
http://example.com/?interval=1d
to
http://example.com/?interval=3d
Doesnt that mean , that my useEffect in ChartContainer should be triggered? WHy isnt it being triggered?