Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

191
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda