简体   繁体   中英

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 setUser method.

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?

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])
      }
    }
  };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM