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

193
Visualizações
How to change a snippets of code from Class Component to Functional Component

Here is the code of the snippet I want to change to a Functional component, I write almost my code here now please check.

import _ from 'lodash';
import { ListItem, SearchBar, Avatar } from 'react-native-elements';
import { getUsers, contains } from './api/index';

function App(props) {

  const [loading, setLoading] = useState(false);   
  const [data, setData] = useState([]);
  const [error, setError] = useState(null);
  const [fullData, setFullData] = useState([]);
  const [query, setQuery] = useState();

  useEffect(() => {
    makeRemoteRequest();
  },[query]);

  const makeRemoteRequest = _.debounce(() => {
    setLoading(true);
    getUsers(20, query)
      .then((users) => {
        setLoading(false);
        setData(users);
        setFullData(users);
      })
      .catch((error) => {
        setLoading(false);
      });
  }, 250);

  const handleSearch = (text) => {
    const formattedQuery = text.toLowerCase();
    const data = _.filter(fullData, (user) => {
      return contains(user, formattedQuery);
    });
   // I want to change the below code to work on Functioanl component
    //  this.setState({ data, query: text }, () => //this.makeRemoteRequest());
   // New code here.....
          };

I implemented it in a different way but not work.

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

0

You're trying to make a set of data and text, then call a callback after the set.

There are several ways to obtain this behaviour.

What I would suggest you is to have a state (useState) which include data and text and then listen for the changes of this stage through a useEffect.

export default function App() {
  const [request, setRequest] = useState({data: {}, text: ''});
  const makeRemoteRequest = useCallback(() => console.log({request}),[request]);
  
  useEffect(() => {
    //on mount 
    setRequest({data: {obj:'with data'}, text: 'text'})
  },[])

  useEffect(() => {
    makeRemoteRequest()
  },[request,makeRemoteRequest])
  
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

What you can see here, it's a functional component which is:

  • setting a state on mount (read comment)
  • define a function makeRemoteRequest every time the state request changes through the useCallback hook
  • call the function makeRemoteRequest every time the state request or the callback makeRemoteRequest changes through the useEffect hook

EDIT:

import _ from 'lodash';
import { ListItem, SearchBar, Avatar } from 'react-native-elements';
import { getUsers, contains } from './api/index';

function App(props) {

  const [loading, setLoading] = useState(false);   
  const [data, setData] = useState([]);
  const [error, setError] = useState(null);
  const [fullData, setFullData] = useState([]);
  const [query, setQuery] = useState();

  useEffect(() => {
    makeRemoteRequest();
  },[query]);

  const makeRemoteRequest = _.debounce(() => {
    setLoading(true);
    getUsers(20, query)
      .then((users) => {
        setLoading(false);
        setData(users);
        setFullData(users);
      })
      .catch((error) => {
        setLoading(false);
      });
  }, 250);

  const handleSearch = (text) => {
    const formattedQuery = text.toLowerCase();
    const data = _.filter(fullData, (user) => {
      return contains(user, formattedQuery);
    });
    setData(data);
    setQuery(text);
  }
};

Actually what you want is to trigger the function makeRemoteRequest, right now that you have to do in order to get it is to make the proper set (which means setQuery), which is going to trigger the useEffect

about 4 years ago · Juan Pablo Isaza Relatório

0

You can have something like the following.

const [query, setQuery] = useState();
const [data, setData] = useState();

useEffect(() => {
  makeRemoteRequest();
}, [query])

Read more about useEffect here

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