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

217
Vistas
react typescript state Object is possibly 'undefined' error

Im new to using typescript with react. I have an application where I call an api and set the response to a state. I have created a generic type for api calls as follow.

const responseBody = <T>(response: AxiosResponse<T>) => response.data;
const restApiCalls = {
  get: <T>(url: string) => axios.get<T>(url).then(responseBody),
  post: <T>(url: string, body: {}) =>
    axios.post<T>(url, body).then(responseBody),
  put: <T>(url: string, body: {}) => axios.put<T>(url, body).then(responseBody),
};

const users = {
  getUsers: () =>
    restApiCalls.get<Users[]>("https://jsonplaceholder.typicode.com/users"),
};

const apis = {
  users,
};
export default apis;

The getUser() function calls the get request and returns a list of Users

The following is the User interface

export interface Users {
  id: boolean;
  name: string;
  username: string;
  email: string;
  address: Address;
  phone: string;
  website: string;
  company: Company;
}

interface Address {
  street: string;
  suite: string;
  city: string;
  zipcode: string;
  geo: Geo;
}

interface Geo {
  lat: string;
  lng: string;
}

interface Company {
  name: string;
  catchPhrase: string;
  bs: string;
}

When calling the api, the api returns the data successfully and I assigned the returned data to the state using setUsermethod.

Following is the state.

const [user, setUser] = useState<Users[]>();

I assigned the fetched data to state as follow.

useEffect(() => {
    const fetchData = async () => {
      const res = await apis.users.getUsers();
      
      setUser(res);
    };
    fetchData();
  }, []);

when console the user state, the data is is there and it is logged successfully. But I want to check the length of the user state in a if condition. If I check the length, it show the following error.

Object is possibly 'undefined'.ts(2532)

This is the code I used to check the length

 const someFunction= () => {
    if (user?.length > 1) {
      for (let index = 0; index < user?.length; index++) {
        console.log(user[index])
      }
    }
  };

But I if set the state type to any instead of User[], it works. WHat might be the issue?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

The expressions with users are all capable of resolving to undefined, which cannot be compared to a number and cannot be indexed. For example user?.length could be undefined (if user is undefined); same with user[index]

You need to handle the undefined case. For example:

 const someFunction= () => {
    if(!user) { return; }
    if (user.length > 1) {
      for (let index = 0; index < user.length; index++) {
        console.log(user[index])
      }
    }
  };
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