Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

203
Visualizações
React Hooks - useFetch generalization

I have an api which provides me methods like:

  1. searchUsersByUsername(username, limit)
  2. getRandomPremiumUsers(limit)
  3. getYoungUsers(maxAge, limit)

I am implementing a hook "useFetchUsers", which will provide an interface to access these methods.

This is my current code:

import { useState, useEffect } from "react";

import {
  searchUsersByUsername, 
  getRandomPremiumUsers,
  getRandomYoungUsers,
} from "../../services/firebase/api/users/search"
import { MAX_SEARCH_USERS_BY_USERNAME_TO_RETRIEVE } from "../../utils/search";

export const QUERIES = {
  "SEARCH_USERS_BY_USERNAME": searchUsersByUsername,
  "FETCH_RANDOM_PREMIUM_USERS": getRandomPremiumUsers,
  "FETCH_RANDOM_YOUNG_USERS": getRandomYoungUsers,
};

const defaultOptions = {
  query: QUERIES[0],
  username: "", // optional
  limit = MAX_SEARCH_USERS_BY_USERNAME_TO_RETRIEVE, // optional
};

export default function useFetchUsers(options = defaultOptions, deps) {
  const [users, setUsers] = useState([]);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState(undefined);

  const getUsers = async () => {
    setIsLoading(true);

    try {
      const users = await options.query();
      setUsers(users);
    } catch(err) {
      setError(err);
    }

    setIsLoading(false);
  }

  useEffect(getUsers, deps);

  return {
    users,
    isLoading,
    error,
    getUsers
  }
}

The main problem I am facing, is that I don't know how to make this "interface" more flexible, in order to be able to pass arguments to my QUERY methods.

Also, my defaultOptions object doesn't need the fields "username" for the methods "getRandomPremiumUsers" and "getRandomYoungUsers".

Any ideas about how to fit the requirements following a similar abstraction?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Create methods and return

export default function useFetchUsers() {
  const initialState = {
    payload: null,
    error: null,
    inFlight: false,
  };
  const [result, setResult] = useState(initialState);
  const searchUsersByUsername = () => {
    setResult({ payload: null, error: null, inFlight: true });
    try {
      const payload = fetch("api");
      setResult({ payload, error: null, inFlight: false });
    } catch (error) {
      setResult({ payload: null, error: null, inFlight: false });
    }
  };
  return {
    ...result,
    searchUsersByUsername,
  };
}

Write an API helper that implements fetching logic

const api = {
  user: {
    searchUsersByUsername: (option) => {
      return fetch(option);
    },
    getRandomPremiumUsers: (option) => {
      return fetch(option);
    },
    getYoungUsers: (option) => {
      return fetch(option);
    },
  },
};

export default function useFetchUsers() {
  const initialState = {
    payload: null,
    error: null,
    inFlight: false,
  };
  const [result, setResult] = useState(initialState);
  
  const updateState = (fetcher, option) => {
    setResult({ payload: null, error: null, inFlight: true });
    try {
      const payload = fetcher(option);
      setResult({ payload, error: null, inFlight: false });
    } catch (error) {
      setResult({ payload: null, error: null, inFlight: false });
    }
  };
  return {
    ...result,
    updateState,
  };
}

function App() {
  const { updateState, payload } = useFetchUsers();
  return (
    <div
      onclick={() =>
        updateState(api.user.searchUsersByUsername, { username: 'name', limit: 10 })
      }
    >
      searchUsersByUsername
    </div>
  );
}

So depending upon your use case you can implement caching in API layer itself or extend it with a context API

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda