Skip to content

Commit 04c1541

Browse files
authored
fix(React IS): fix back button behaviour with basic and seo friendly routing (#337)
* fix(React IS): fix back button behaviour with seo friendly routing This change fixes the behaviour of the back button in SEO friendly routing example Prior to this change, the example was missing the bit that updates the externally managed searchState when location changes: ```jsx const [searchState, setSearchState] = useState(urlToSearchState(location)); useEffect(() => { setSearchState(urlToSearchState(location)); }, [location]); ``` fixes [FX-246](https://algolia.atlassian.net/browse/FX-246) * fix(React IS): fix back button behaviour with basic routing * useRef instead of variable
1 parent 66e95b5 commit 04c1541

File tree

2 files changed

+15
-9
lines changed
  • React InstantSearch

2 files changed

+15
-9
lines changed

React InstantSearch/routing-basic/src/App.js

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import React, { useRef, useState } from 'react';
1+
import React, { useEffect, useRef, useState } from 'react';
22
import {
33
InstantSearch,
44
Hits,
@@ -39,6 +39,10 @@ export function App({ location, history }) {
3939
setSearchState(updatedSearchState);
4040
}
4141

42+
useEffect(() => {
43+
setSearchState(urlToSearchState(location));
44+
}, [location]);
45+
4246
return (
4347
<div className="container">
4448
<InstantSearch

React InstantSearch/routing-seo-friendly/src/App.js

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import React, { useState } from 'react';
1+
import React, { useEffect, useRef, useState } from 'react';
22
import {
33
InstantSearch,
44
Hits,
@@ -135,20 +135,22 @@ Hit.propTypes = {
135135

136136
const App = ({ location, history }) => {
137137
const [searchState, setSearchState] = useState(urlToSearchState(location));
138-
const [debouncedSetState, setDebouncedSetState] = useState(null);
138+
const debouncedSetStateRef = useRef(null);
139139

140140
const onSearchStateChange = updatedSearchState => {
141-
clearTimeout(debouncedSetState);
141+
clearTimeout(debouncedSetStateRef.current);
142142

143-
setDebouncedSetState(
144-
setTimeout(() => {
145-
history.push(searchStateToUrl(updatedSearchState), updatedSearchState);
146-
}, DEBOUNCE_TIME)
147-
);
143+
debouncedSetStateRef.current = setTimeout(() => {
144+
history.push(searchStateToUrl(updatedSearchState), updatedSearchState);
145+
}, DEBOUNCE_TIME);
148146

149147
setSearchState(updatedSearchState);
150148
};
151149

150+
useEffect(() => {
151+
setSearchState(urlToSearchState(location));
152+
}, [location]);
153+
152154
return (
153155
<div className="container">
154156
<InstantSearch

0 commit comments

Comments
 (0)