0

I have this useEffect:

const [newMessage, setNewMessage] = useState(false);
const [data, setData] = useState();

useEffect(() => {
    getData();
}, []);

So my getdata() calls once and inside this get data I have this:

    const getData = () => {
        let isReply = false;
        if(!route.params.messageId == 0){
            isReply = true;
        }
        fetch('xxxxx?guid=' + route.params.id + '&isReply=' + isReply + '&messageId=' + route.params.messageId + "&userId=1", {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json'
            }})
        .then(function(response){
            return response.json();
        })
        .then(function(json){
            console.log(JSON.stringify(json));
                setData(json["messages"]);
                setNewMessage(false);
                setLoading(false);
        })
        .catch(function(error) {
            throw error;
        });
    }

As you can see that setData() is called so then the timer interval will start once setNewMessage(false) is called and newMesage is flase initially :

    useEffect(() => {
        if(!newMessage){
            startInterval();
        }else{
        }
    }, [newMessage, loading]);

Inside the interval call I have this:

const startInterval = () =>{
    intervalId.current = setInterval(() => {
        getMessagesRepliesRefresh();
      }, 10000);
}

So when the interval runs it calls getMessagesRepliesRefresh()

And this is the getMessagesRepliesRefresh():

    const getMessagesRepliesRefresh = () => {
        if(!newMessage){
            let isReply = false;
            if(!route.params.messageId == 0){
                isReply = true;
            }
            fetch('xxxxx?id=' + data[0]["message"]["mess"].id + '&guid=' + route.params.id + '&isReply=' + isReply + '&messageId=' + route.params.messageId + "&userId=1", {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json'
                }})
            .then(function(response){
                return response.json();
            })
            .then(function(json){
                if(json["count"] > 0){
                     clearInterval(intervalId.current);
                     setNewMessage(true);
                }
            })
            .catch(function(error) {
                console.log('There has been a problem with your fetch operation: ' + error.message);
                // ADD THIS THROW error
                throw error;
            });
        }
    }

Im clearing the timer becuase the code states the value is greater than 0 so that means a new message has been added in the database so stop the interval for querying getMessagesRepliesRefresh() function until onNewMessage() has been invoked again and the timer will start again.

This code in the URL inside fetch above stated does not get the value in 0 position (from setData that has the data variable set against it), the value below stated is always the previous value even when getData() is called within onNeMessage() and the setData does populate the new id in position 0 as I have seen this in console.log :

data[0]["message"]["mess"].id


const onNewMessage = () => {
    getData();
}

The data[0]["message"]["mess"].id should be the current value when getData() again is called stated after the clearinterval call here:

if(json["count"] > 0){
      clearInterval(intervalId.current);
      setNewMessage(true);
}

so why is the data[0]["message"]["mess"].id still the previous value even when the new data has been populated?

Its difficult to explain this but I hope you guys understand the question and know what is happening.

redoc01
  • 2,107
  • 5
  • 32
  • 64
  • 1
    Also, not mentioned in that question, but a Reacty way to handle this is useCallback with the state value in the dependency array. That will recreate the function every time the state changes. – Abe Jun 27 '23 at 23:57
  • 1
    stylistically, you only need quotes around object properties when they have special characters in them. `json.count`, `data[0].message.mess.id` are easier. `'Content-Type': 'application/json'` still needs quotes – Abe Jun 28 '23 at 00:01
  • thank you that answered my question, now works. using useCallback – redoc01 Jun 28 '23 at 00:09

0 Answers0