KARTHIKEYAN.A
KARTHIKEYAN.A

Reputation: 20108

How to call api twise / more then one time if untill I resive the data from response in reactjs

In my react application I'm calling api call some times I'm not receiving data from api specifically in 1st time call. In this case while I do a second api call I'm receiving result always. How to resolve the issue.

useEffect(() => {
    post(`get-${props.url}`, {searchParams: {UserId: props.userId}})
        .then(response => {
            if (Object.keys(response.data).length === 0) {
                recursiveCall()
            }
            console.log(response, 'response')
        })
        .catch(error => {
            console.log(error, 'error')
        })
}, [ ])

Upvotes: 0

Views: 38

Answers (2)

giamir
giamir

Reputation: 136

I would first focus on finding out the root cause of the problem. If the API is something you control I would start from there and check why the server is giving you a response only on your 2nd requests and not the 1st ones.

If you can't fix the root cause then you might want to use a retry algorithm with exponential backoff to avoid overloading the server with too many requests.

Building on top of your initial solution exponential backoff would look something like this:

useEffect(() => {
    const recursiveCall = (depth = 1) => {
        post(`get-${props.url}`, {searchParams: {UserId: props.userId}})
            .then(response => {
                if (Object.keys(response.data).length === 0) {
                    setTimeout(() => recursiveCall(depth + 1), 2 ** depth * 1000)
                }
                console.log(response, 'response')
            })
            .catch(error => {
                console.log(error, 'error')
            })
    }
    recursiveCall()
}, [ ])

// Call nr. | Delay
//        1 |    0s
//        2 |    2s
//        3 |    4s
//        4 |    8s
// ...and so on

You might want to consider extracting the backoff mechanism in a utility function instead of keeping it hardcoded in the useEffect hook.

Upvotes: 1

KARTHIKEYAN.A
KARTHIKEYAN.A

Reputation: 20108

I made solution after thinking the problem. I'm my api call I alway getting response in 2nd time so I thought to use recursion concept to resolve the issue. After implementing the solution it work as I expected way.

useEffect(() => {
    let rcCount = 0
    const recursiveCall = () => {
        post(`get-${props.url}`, {searchParams: {UserId: props.userId}})
            .then(response => {
                rcCount += 1
                if (Object.keys(response.data).length === 0 && rcCount < 4) {
                    recursiveCall()
                }
                console.log(response, 'response')
            })
            .catch(error => {
                console.log(error, 'error')
            })
    }
    recursiveCall()
}, [ ])

Upvotes: 1

Related Questions