Posts

Showing posts from August, 2024

How to retry a failed promise in Javascript?

The problem: When a promise fails, we want to handle it by retrying it's request. We solve it by using recursion. We need to implement 2 functions. The first would be the delay function, the other would be the promise function Delay function: function wait ( t ) {     return new Promise (( resolve ) => setTimeout ( resolve , t * 1000 ));   } Promise function const promise = ( tries , delay ) => {     function onError ( err ) {       tried = tries - 1 ;       if ( ! tried ) {         throw err ;       }       return wait ( t ). then (() => promise ( tries , delay ));     }     return promise . catch ( onError );   }; Get the result by simply calling like this: promise ( 5 , 5 ). then ( result => console . log ( result ))

429 (Too Many Requests) Error when using public API in React

  The problem: When calling a public API in useEffect, it will throw a 429 (Too Many Requests) error. Why does it happen? There are a few reasons.  It depends on the API It is caused by Strict mode being turned on Some API limits the user's call interval to regulate the traffic. Also, if strict mode is turned on, useEffect will be called twice. Therefore, the solution would be: Turn off strict mode. Extend the API request interval. Rerun the API call by refreshing the page or implement a API request retry function. 

Why is reducer not updating states in React?!

 The problem: Updating the state with useReducer doesn't update state. Look at the code below:   const quizReducer = async ( state , action ) => {     switch ( action . type ) {       case POPULATE :         return { ... state , questions : action . payload , ready : true };     }   };   const [{ questions , ready }, dispatch ] = useReducer ( quizReducer , intialState );    useEffect (() => {     if ( controller . current !== null ) return console . log ( "Hello" );     controller . current = new AbortController ();     fetch ( `http://localhost:3000/api/v1/bootcamps` )       . then (( res ) => res . json ())       . then (( result ) => {         const data = result . data ;         dispatch ({ type : POPULATE , payload : data });       })   ...