简体   繁体   中英

Requiring a Hook to update on state change

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;

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM