Home > Blockchain >  Requiring a Hook to update on state change
Requiring a Hook to update on state change

Time:05-08

So this is a component I have in React JS

const EnterSetData = ({ user_card_set }) => {
  const [cardlist, setCardlist] = useState({ data: [] });

  let setlist= useGetSetDB();

  //Save and reset form
  const sendSets = () => {   
    const dupes = findDuplicates(setlist, cardlist); 
    if (dupes.length > 0) {
     saveSets(setlist)
     setCardlist({ data: [] });
    } else {
      handleDupes(dupes);
    }
  };

useEffect(() => {
    setCardlist(card_set);
  }, [card_set]);

return (
    <>
  {cardlist.data.map((card, key) => (
            <a> .......</a>))}

        <button 
         type="button"
          onClick={sendSets}
        >
          Save Cards
        </button>
      </div>

The main issue is while data is saved, there is a major bug. useGetSetDB() is used to fetch the entire set list from an API. After saving, I use setCardlist to update the component state. It is here that I notice that setlist does not change. The new entries are not there and this causes findDuplicates to fail. My DB checks for duplicates, and thus console.logs will show that the inserts failed. How do I force useGetSetDB to update on every state change.This is useGetSetDB

const useGetSetDB = () => {
    const[state,setState] = useState([]);

    const fetchData = async () => {
        const data = await fetch("/sets");
        const res = await data.json();        
        return res;
      };
      
      useEffect(()=>{
        fetchData().then(response => {setState(response)})
      },[])

  return state
}

export default useGetSetDB;

CodePudding user response:

You can pass cardlist to useGetSetDB like below

const [cardlist, setCardlist] = useState({ data: [] });
let setlist = useGetSetDB(cardlist); //whenever cardlist gets updated, we trigger side-effect again

You also need to modify useGetSetDB to align with state change

const useGetSetDB = (cardlist) => {
    const[state,setState] = useState([]);

    const fetchData = async () => {
        const data = await fetch("/sets");
        const res = await data.json();        
        return res;
      };
      
      useEffect(()=>{
        fetchData().then(response => {setState(response)})
      }, [cardlist]) //add `cardlist` to dependency list

  return state
}

export default useGetSetDB;
  • Related