Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Calculadora

0

85
Vistas
empty useState on request React

I am using a button to perform a fetch request, when I do it and try to set the response in useState it always stays empty but if I click the button again now it sends me the information correctly.

This is my code:


  const fetchUsers = async (page, limit = perPage, search = searchBox, type) => {

    if (type === 'all') {
      limit = 100000
    } else {
      setLoading(true);
    }

    const dataOnLs = localStorage.getItem('cmtjs')

    const config = {
      headers: {
          "Content-Type": "application/json",
          apiKey: dataOnLs
      } ,
      params: {
          limit,
          page, 
          search
        }            
  }
    const response = await axiosClient(`/products`, config)
    console.log(response.data.products.docs); // DATA OK
    if (type === 'all') {
      setDataToXLS(response.data.products.docs); // **EMPTY**
    } else {
      setData(response.data.products.docs); // DATA OK
      setTotalRows(response.data.products.totalDocs);
      setLoading(false);
    }
  };

I don't understand why it doesn't set my useState (setDataToXLS) with the data on the first click and I have to click twice to get the data correctly

7 months ago · Santiago Gelvez
Responde la pregunta
Encuentra empleos remotos