Home > Net >  How to call custom hook useFetch with different query per render?
How to call custom hook useFetch with different query per render?

Time:08-21

I've got a component, Crafts.js, which calls for useFetch() with a firestore query as an argument:

const q = query(craftsColRef, where("category", "==", currPage));

const { data:crafts, setData:setCrafts, mats, setMats } = useFetch(q);

The third argument of where() in the query is a prop passed to crafts component which is updated in a parent component. The currPage prop does update with the new value, but I think it's clear that React doesn't call useFetch on re-render, therefore I don't get the new data. I'm trying to achieve some kind of navigation. User clicks a button and the docs are filtered in a different way. How can I achieve this? Thank you!

CodePudding user response:

I am not sure what is written in your useFetch but you can write your custom hook and from my understanding of your logic flow, I made a sample code. Hope it helps

import { useEffect, useState } from "react";

function firestoreQuery(currPage) {
  // since this is just a fake api
  // please change it to your query logic here
  return new Promise(resolve => {
    resolve([1, 2, 3, 4, 5, 6, 7, 8, 9, 10].sort(() => Math.random() - 0.5));
  })
}

// Your custom hook
function useCustomFetch(currPage) {
  const [items, setItems] = useState([]);

  async function fetch() {
    let result = await firestoreQuery(currPage);

    setItems(result);
  }

  useEffect(() => {
    if (!currPage) return;
    console.log("fetch")
    fetch();
  }, [currPage]);

  return { items };
}

function Craft({ currPage }) {
  const { items } = useCustomFetch(currPage);

  return <div>
    {items.map(i => <span>{i}</span>)}
  </div>
}

function ParentComponentPage() {
  const [timestamp, setTimestamp] = useState();

  return <div>
    <button onClick={() => setTimestamp(new Date().getTime())}>Change currPage</button>
    <Craft currPage={timestamp} />
  </div>
}

export default ParentComponentPage;
  • Related