Skip to content

Handy React/ React-Native snippets

  • Show time between requests
  • 
    app.use((req, res, next) => {
      console.log(`${req.method} ${req.originalUrl} [STARTED]`);
      const getDurationInMilliseconds = (start) => {
      const NS_PER_SEC = 1e9;
      const NS_TO_MS = 1e6;
      const diff = process.hrtime(start);
    
      return (diff[0] * NS_PER_SEC + diff[1]) / NS_TO_MS;
      };
      const start = process.hrtime();
    
      res.on('finish', () => {
        const durationInMilliseconds = getDurationInMilliseconds(start);
        console.log(`${req.method} [FINISHED] ${durationInMilliseconds.toLocaleString()} ms`);
      });
    
      res.on('close', () => {
        const durationInMilliseconds = getDurationInMilliseconds(start);
        console.log(`${req.method}  [CLOSED] ${durationInMilliseconds.toLocaleString()} ms`);
      });
    
      next();
    });
    
  • Memo/li>
    const defaultCacheExpiration = 3600;
    
    const dataEmpty = data => (!data || (Array.isArray(data) && !data.length));
    
    const createMemoizer = ({ expirationSeconds = defaultCacheExpiration, rejectFromCacheFn } = {}) => {
      const memoizationCache = {};
      return {
        memoize: async (key, retrieveData) => {
          const cachedResult = memoizationCache[key] && [memoizationCache[key]]
            .find(({ expiration }) => expiration && expiration > new Date());
          if (cachedResult) return cachedResult.data;
          const data = await retrieveData(key);
          if (rejectFromCacheFn && rejectFromCacheFn(data)) return data;
          memoizationCache[key] = {
            expiration: new Date(new Date().getTime() + expirationSeconds * 1000),
            data,
          };
          return data;
        },
      };
    };
    
    module.exports = { createMemoizer, dataEmpty };
    
    
  • Add network request (with fetch)
    somefile.js

    async function getMoviesFromApi() { console.log(‘getting’) try { let response = await fetch( ‘https://facebook.github.io/react-native/movies.json’ ); let responseJson = await response.json(); console.log(responseJson.movies); } catch (error) { console.error(error); } }

  • Show network requests in console + network tab chrome
    app.js

    // To see all the requests in the chrome Dev tools in the network tab. XMLHttpRequest = GLOBAL.originalXMLHttpRequest ? GLOBAL.originalXMLHttpRequest : GLOBAL.XMLHttpRequest; // fetch logger global._fetch = fetch; global.fetch = function (uri, options, …args) { return global._fetch(uri, options, …args).then((response) => { console.log(‘Fetch’, { request: { uri, options, …args }, response }); return response; }); };

Published inReactReact nativeUncategorized

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *