0

I am working on React hook and when i set dependency on useEffect it trigger all time,but it should trigger only when there will be some changes in Json API, Here is my code so far i did.How to make it that its trigger only when new changes will be in API.

Thanks

const [data, setData] = useState([]);
  useEffect(() => {
    const getdata = () => {
      fetch(config.auth.notification_list, config.head)
        .then((response) => response.json())
        .then((data) => {
          setData(data);
        });
    };

    getdata();
  }, [data]);
Piotr
  • 145
  • 4
  • 16
  • 1
    Looks like your code example doesn`t make a lot of sense. This can case an infinite loop. Make a call to api each time when data changed and than change data. – Taras Kumpanenko Dec 22 '20 at 12:49
  • 1
    How will your app know that there are "some changes in the API"? – Konstantin Dec 22 '20 at 13:01
  • are you asking how to detect change in the server? it seems the socket io or some sort of notification from the server side is required... am i right? – adir abargil Dec 22 '20 at 13:21
  • I am asking that if there will be new data in API it should automatically update fetch. don't need to refresh the page then get data @adirabargil – Piotr Dec 22 '20 at 13:36
  • of course not... but how do plan to know when the data is changing? are you planning to fetch it endlessly until there is a change? – adir abargil Dec 22 '20 at 13:37
  • Not, I want to just update API data when there will be in list. – Piotr Dec 22 '20 at 13:44

1 Answers1

0

As you want to "trigger only when ... changes ...", you need to set data only if these changes happen.

Here you need to implement dataHasChanged( data ) according to your needs (you didn't specify what "API change" means exactly).

const [ data, setData ] = useState([]);
useEffect(() => {
  fetch( /*...*/ )
    .then(( data ) => {

      if( dataHasChanged( data ) ){  // <----- only set data if necessary
        setData( data );
      }

    });
}, [ data ]);

Alternatively (if appropriate for your use case), you might only fetch the new data if you know it might have changed:

const [ data, setData ] = useState([]);
useEffect(() => {

  if( !newDataNeedsToBeFetched( data ) ){ // <----- skip if no fetch necessary
    return;
  }

  fetch( /* ... */ )
    .then(( data ) => {
      setData( data );
    });
}, [ data ]);

implement hasChanged()

How to determine if data has changed in javascript is a separate question. Maybe you even don't have a problem there, otherwise please refer to other answers about that, e.g. design-pattern-to-check-if-a-javascript-object-has-changed.

You might also want to know about using useRef() to store the previous value: how-to-compare-oldvalues-and-newvalues-on-react-hooks-useeffect

kca
  • 4,856
  • 1
  • 20
  • 41