Home > Net >  Property 'aboutData' does not exist on type 'never[]'
Property 'aboutData' does not exist on type 'never[]'

Time:02-21

What is the best way to print array items? It's return error "Property 'post_title' does not exist on type 'never[]'".

How to use interface to define these variables and use them in code for both aboutData and executive array items.

API resoponse

{
    "aboutData": {
        "post_id": 18,
        "post_title": "Established since 2014",
    },
    "executive": [
        {
            "post_id": 39,
            "post_title": "Quality and excellence in everything we do.",
        },
    ],
}

Here is the component file:

const About: React.FC = () => {

    const history = useHistory();
    const [showLoading, setShowLoading] = useState(true);
    const { authValues, setAuthValues } = React.useContext(userContext);
    const [data, setData] = useState([]);

    React.useEffect(() => {
        getAbout();
    }, []);

    const getAbout = async () => {
        setShowLoading(true);

        return api
            .getabout()
            .then((response) => {
                setData(response.data.data);
                console.log(response.data.data);
            })
            .catch((error) => {
                console.log(error);
            });
    };    

    return (
        <IonPage>

      <IonContent fullscreen>
        <IonCard>
          <IonCardContent>
            <IonList className="dash_grid">
               <IonItem>
              <IonLabel>{data.aboutData.post_title}</IonLabel>
              </IonItem>
            </IonList>
            <IonList color="primary" className="history_box">
              {data.executive.length > 0 ? (
                data.executive.map((exec) => {
                  return (
                    <IonItem>
                        <IonText color="medium">{exec.post_title}</IonText>
                    </IonItem>
                  );
                })
              ) : null}
            </IonList>
          </IonCardContent>
        </IonCard>
      </IonContent>
    </IonPage>
    );
};

export default About;

CodePudding user response:

You should add optional chaining when using map "?". Add it after data.

  {data?.executive.length > 0 ? (
            data?.executive.map((exec) => {

CodePudding user response:

You inited your data in the wrong way. That was not an array. Change into this

    const [data, setData] = useState(null);
    ...
    if(!data) return null; // you can handle the loading page here when data is not ready yet

    return (
        ...
    )
  • Related