Home > Mobile >  Next/React: How to store fetched data from backend (Sanity) in localstorage?
Next/React: How to store fetched data from backend (Sanity) in localstorage?

Time:09-11

I have a gallery page that shows 6 categories (as images that are used as links) that, when one is selected, will move onto the next page and show a list of referenced sets. The next page should show the category name that was selected.

I'm currently trying to store the category name (which is located in my backend) into local storage once it is clicked, which I can then extract into the next page. This is what I currently have:

import React, { useState, useEffect } from 'react';
import { client, urlFor } from '../lib/client';
import { Header, Footer } from '../components';
import Link from 'next/link';

const gallery = () => {

  // fetches sanity data

  const [categoryData, setCategories] = useState(null);

  useEffect(() => {
    client.fetch(
        `*[_type=="category"]{
            categoryImage_alt,
            category_image{
            asset->{
                _id,
                url
                }
            },
            category_name,
            contained_sets
        }`)
        .then((data) => setCategories(data))
        .catch(err => console.error(err));
  }, [] );

  const selectedCategory = [];
  const saveCategory = (e) => {
      selectedCategory.push({})
      localStorage.setItem('selectedCategoryName', JSON.stringify(selectedCategory));
      console.log(localStorage)
  }

  return (
    <div>
    <Header />
    <main className="main-gallery"> 
      <div className="title">
          <div className="title-line-left"></div>
          <h2>categories</h2> 
          <div className="title-line-right"></div>
      </div>
      <div className="categories">
          <ul className="categories-container">
            {categoryData && categoryData.map((category, index) => (
                <li key={index}>
                    <Link href="/sets"><img src={urlFor(category.category_image).auto('format').url()} alt={category.categoryImage_alt} onClick={saveCategory(category.category_name)} /></Link>
                </li>
            ))}
          </ul>
      </div>
    </main>
    <Footer />
    </div>
  )
}

export default gallery

(I've also tried putting the onClick event in the Link tag instead of the img tag, same result). At the moment however, it doesn't store anything when the category is clicked. Instead, when I click onto the navbar menu that opens up this page with categories, it immediately prints out this 6 times (and nothing happens when I click onto one of the categories): enter image description here

CodePudding user response:

replace your saveCategory function with

  const saveCategoryName = (categoryName) => {
      localStorage.setItem('selectedCategoryName', categoryName);
  }

and replace the onclick function with

onClick={() => saveCategoryName(category.category_name)}

now selected category name will stay in localStorage

  • Related