[Solved] Preserving prior form data when navigating back in Gatsbyjs


I ended up setting up an onClick listener on the filter where if a user clicks it will create a query string and navigate to the same page but with query parameters.

Then on page load I read the location.search with contains the query, then parse the query and set the page state from the query. This way when the user refreshes the page or navigates to another page and comes with the back button to the original page, the selected filters are preserved.

Here the code:

const ProductPage = (props) => {
    const { products, breadcrumb } = props.pageContext
    const {location} = props
    const filter = qs.parse((location.search).substring(1))
    
    const initialFilter = {
      brands: [],
      types: [],
      ages: [],
      breeds: [],
      features: [],
      petTypes: [],
  }
  const filtered = Object.assign({},initialFilter,filter)
  const handleChange = (event, group) => {
      let checkedOptn = [...filtered[group]]
      let optionsSelected = {
        ...filtered,
        [group]: checkedOptn.indexOf(event.target.name) > -1 ? checkedOptn.filter(item => item !== event.target.name) :
            [...checkedOptn, event.target.name]

    }
    let queryString = qs.stringify(optionsSelected)
    console.log(queryString)
    const path = queryString.length > 0 ? `/urunler?${queryString}` :'/urunler'
      navigate(path)
  }
    
    const pageTitle = () => {
      if (location.pathname==='/urunler/kedi') {return 'Kedi Ürünlerimiz'}
      if (location.pathname==='/urunler/kopek') {return 'Köpek Ürünlerimiz'}
      return 'Ürünlerimiz'
    }
    
    return (
    <Layout location={location} pageTitle = {pageTitle()} crumbs={breadcrumb.crumbs}>
       <ProductList products = {products} checked={filtered} handleChange={handleChange}/>
    </Layout>
    )
}

export default ProductPage

solved Preserving prior form data when navigating back in Gatsbyjs