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

110
Visualizações
Use of custom API hooks with updating search terms

I'd like to use custom api request hook like so

// hooks.js
import { useState, useEffect } from 'react';
import api from '../utils/api';

function useAPI(fn, payload) {
    const [state, setState] = useState({
        loading: false,
        data: null,
        error: null,
    });

    const callAPI = async () => {
        const setAPIState = update => setState({ ...state, ...update });
        try {
            setAPIState({ loading: true });
            const data = await fn(payload);
            setAPIState({ data, loading: false });
        } catch (error) {
            setAPIState({ error, loading: false });
        }
    };

    useEffect(() => {
        callAPI();
    }, [fn, payload]);

    return state;
}

export const useFetchTransactions = payload => {
    const fetchTransactions = api.fetchTransactions;
    return useAPI(fetchTransactions, payload);
};

and call it within my React component like so:

// Component.jsx
import { useState } from 'react';
import { useFetchTransactions } from '../hooks.js';

export default const Component = () => {
    const [id, setID] = useState('');
    const [date, setDate] = useState('12/13/21');

    const { loading, data, error } = useFetchTransactions({ id, date });
    
    return (
      <div>{data.map...}</div>
    )
}

However, this looks wrong. I think useFetchTransactions should live inside of a useEffect, so that the component then becomes something like:

// Updated Component.jsx
import { useState, useEffect } from 'react';
import { useFetchTransactions } from '../hooks.js';

export default const Component = () => {
    const [id, setID] = useState('');
    const [date, setDate] = useState('12/13/21');
    const [apiState, setApiState] = useState({
        data: null,
        error: null,
        loading: false
    })

    useEffect(() => {
        const result = useFetchTransactions({ id, date });
        setState({ ...apiState, ...result });
    }, [date, id])
    
    return (
      <div>{apiState.data.map...}</div>
    )
}

But the above feels cumbersome and redundant. Can anyone please lend some knowledge on this? Thanks!

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

0

you can do it like this

 function useAPI(fn) { const [state, setState] = useState({ loading: false, data: null, error: null, }); const callAPI = async (payload) => { const setAPIState = update => setState({ ...state, ...update }); try { setAPIState({ loading: true }); const data = await fn(payload); setAPIState({ data, loading: false }); } catch (error) { setAPIState({ error, loading: false }); } }; return {state, callAPI}; } export const useFetchTransactions = () => { const fetchTransactions = api.fetchTransactions; return useAPI(fetchTransactions); };

And then in your component

 import { useState } from 'react'; import { useFetchTransactions } from '../hooks.js'; export default const Component = () => { const [id, setID] = useState(''); const [date, setDate] = useState('12/13/21'); const { callAPI, loading, data, error } = useFetchTransactions(); useEffect(() => { callAPI({ id, date }) }, [date, id]) return ( <div>{data.map(callAPI)}</div> ) }
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